javaconfig的实现
```
@Configuration
public class AppConfig {
@Bean
public UserDAO userDAO()
{
return new UserDAO();
}
@Bean
public UserService userService()
{
UserService userService = new UserService();
userService.setUserDAO(userDAO());
return userService;
}
}
```
java类的实现
```
public class UserService {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO)
{
this.userDAO = userDAO;
}
public void test()
{
System.out.println(userDAO);
}
}
```
```
public class UserDAO {
}
```
测试类的实现
```
@Test
public void testIOC5()
{
//1. 启动spring ioc的容器(BeanFactory, ApplicationContext)
//BeanFactory尽量晚的实例化对象,等到getBean()的时候再实例化。
//applicationContext:尽量早的实例化对象,启动的时候,把单例的类都实例化好。非单例的类,等到第一次调用getBean实例化
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
//2.
UserService userService = ctx.getBean(UserService.class);
UserService userService2 = ctx.getBean(UserService.class);
System.out.println(userService);
System.out.println(userService2);
//userService.test();
}
```