您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
11-Spring配置文件-依赖注入1(bean的嵌套调用)
发布时间:2024-12-18 20:24:54编辑:雪饮阅读()
-
使用bean获取implement的实例还可以支持嵌套的形式,例如我有UserDaoImpl实现UserDao
package com.dao.impl;
import com.dao.UserDao;
public class UserDaoImpl implements UserDao {
public UserDaoImpl(){
System.out.println("-----UserDaoImpl被创建--------");
}
public void save() {
System.out.println("-----UserDaoImpl save--------");
}
public void init(){
System.out.println("执行了init方法");
}
public void destroy(){
System.out.println("执行了destroy方法");
}
}
然后我用UserServiceImpl实现UserService然后去调用UserDao的save方法
package com.service.impl;
import com.dao.UserDao;
import com.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserServiceImplement implements UserService {
public void save() {
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao= (UserDao) app.getBean("userDao");
userDao.save();
}
}
然后最后假定我们的入口类去调用UserService的save方法
package com.web;
import com.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Index {
public static void main(String[] args) {
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService= (UserService) app.getBean("userService");
userService.save();
}
}
那么我们的Spring Config配置文件则如:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="com.dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="com.service.impl.UserServiceImplement"></bean>
</beans>
关键字词:bean,嵌套,spring