将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));
    }
  }
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐