Spring中Bean注入属性的四种方式
public interface UserDAO {
public void insert();
}
public class UserDAOImpl implements UserDAO{
public UserDAOImpl(){
System.out.println(this + "已创建");
}
public void insert() {
System.out.println(this + ":正在调用UserDAOImpl.insert()");
}
}
public class UserService {
private UserDAO userDAO;
public UserService() {
System.out.println(this + "已创建");
}
//通过构造函数注入
public UserService(UserDAO userDAO) {
this.userDAO = userDAO;
System.out.println(this + ":正在调用构造函数注入,UserService(" + userDAO + ")");
}
//通过Setter方法注入
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
System.out.println(this + ":正在调用Setter方法注入,setUserDAO(" + userDAO + ")");
}
public void createUser(){
System.out.println(this + ":正在调用UserService.createUser()");
userDAO.insert();
}
}
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:xxx.xml");
UserService userService = (UserService) context.getBean("userService");
userService.createUser();
}
1、setter方法注入
<bean id="userDAO" class="UserDAOImpl"/>
<bean id="userService" class="UserService">
<property name="userDAO" ref="userDAO"/>
</bean>
UserDAOImpl@564718df已创建
UserService@51b7e5df已创建
UserService@51b7e5df:正在调用Setter方法注入,setUserDAO(UserDAOImpl@564718df)
UserService@51b7e5df:正在调用UserService.createUser()
UserDAOImpl@564718df:正在调用UserDAOImpl.insert()
需要编写setter方法,在运行时Spring自动将IOC容器中的userDAO对象通过反射机制注入到setUserDAO()方法的参数中。
2、构造器注入
<bean id="userDAO" class="UserDAOImpl"/>
<bean id="userService" class="UserService">
<constructor-arg name="userDAO" ref="userDAO"/>
</bean>
UserDAOImpl@770c2e6b已创建
UserService@ca263c2:正在调用构造函数注入,UserService(UserDAOImpl@770c2e6b)
UserService@ca263c2:正在调用UserService.createUser()
UserDAOImpl@770c2e6b:正在调用UserDAOImpl.insert()
需要编写带参构造函数,不推荐使用。假如在程序执行前没有准备好userDAO,则userService无法被创建。
3、注解注入
<context:component-scan base-package="xxx"/>
@Repository("userDAO")
public class UserDAOImpl implements UserDAO {
...
}
@Service //@Service("userService")
public class UserService {
@Resource(name = "userDAO") //优先按照Bean id加载对象
private UserDAO userDAO;
...
}
UserDAOImpl@2db7a79b已创建
UserService@8e24743已创建
UserService@8e24743:正在调用UserService.createUser()
UserDAOImpl@2db7a79b:正在调用UserDAOImpl.insert()
不强制要求setter方法,在IOC容器的初始化过程中完成自动创建、注入的工作。
4、Java Config注入
Java Config注入是在Spring4以后,新推出的一种对象创建与注入的方式。它摒弃了以前的xml文件配置的方式,采用“注解”+“Java代码”方式管理对象关系。
@Configuration
public class AppConfig {
@Bean(name = "userDAO") //默认用方法名作Bean id
public UserDAO userDAO(){
return new UserDAOImpl();
}
@Bean(name = "userService")
public UserService userService(){
UserService userService = new UserService();
userService.setUserDAO(this.userDAO());
return userService;
}
}
UserDAOImpl@275710fc已创建
UserService@75f9eccc已创建
UserService@75f9eccc:正在调用Setter方法注入,setUserDAO(UserDAOImpl@275710fc)
UserService@75f9eccc:正在调用UserService.createUser()
UserDAOImpl@275710fc:正在调用UserDAOImpl.insert()
相对于注解注入的优势
1、不破坏原始代码,不在原始代码中添加任何东西
2、解决了xml文件配置时,编译器无法及时检查的问题。
发表回复