将new Object()注入到Spring容器并实现依赖注入
将new Object()注入到Spring容器public class UserDao {@ResourceAccountService accountService;public void print(){System.out.println(accountService);}}比如有以上这个类,实现将new UserDao()放入Sp
·
将new Object()注入到Spring容器并实现依赖注入
public class UserDao {
@Resource
AccountService accountService;
public void print(){
System.out.println(accountService);
}
}
比如有以上这个类,实现将new UserDao()
放入Spring容器中(放入工作由DefaultListableBeanFactory
完成),并且AccountService
会自动注入(注入工作由AutowireCapableBeanFactory
完成)。
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class test{
@Autowired
private AutowireCapableBeanFactory beanFactory;
@Autowired
DefaultListableBeanFactory defaultListableBeanFactory;
public void testmenualInject(){
UserDao userDao=new UserDao();
//将new出的对象放入Spring容器中
defaultListableBeanFactory.registerSingleton("userDao",userDao);
//自动注入依赖
beanFactory.autowireBean(userDao);
userDao.print();
//判断new的对象和从容器中拿出的对象是否一致
System.out.println(defaultListableBeanFactory.getBean("userDao").equals(userDao));
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)