相关测试类:
@Repository
@Scope("prototype")
public class UserDaoImpl implements UserDao {
public void find() {
System.out.println("dao: "+this.hashCode());
}
}
@ComponentScan("com.liaoxiang")
public class AppConfig {
}
@Service
public class UserService {
@Autowired
private UserDao userDao;
public void find(){
System.out.println("service="+this.hashCode());
System.out.println("dao="+userDao.hashCode());
}
}
public class UserController {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
UserDaoImpl userDao1 = (UserDaoImpl)ac.getBean("userDaoImpl");
UserDaoImpl userDao2 = (UserDaoImpl)ac.getBean("userDaoImpl");
System.out.println(userDao1.hashCode());
System.out.println(userDao2.hashCode());
UserService service1 = (UserService)ac.getBean("userService");
UserService service2 = (UserService)ac.getBean("userService");
service1.find();
service2.find();
}
}
输入结果:
可以看到由于UserService是单例的,在UserService中使用的userDao对象也是单例的,这是因为Spring容器在启动的时候,UserService对象只实例化一次,因此属性的注入也只有一次机会。
如果想要在UserService中使用多例的UserDao实现类对象有两种方式:
1、需要实现ApplicationContextAware
接口
@Service
public class UserService implements ApplicationContextAware {
private ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void find(){
UserDap userDao = (UserDao)applicationContext.getBean("userDaoImpl");
System.out.println("service="+this.hashCode());
System.out.println("dao="+userDao.hashCode());
}
2、使用@Lookup
注解
@Service
public abstract class UserService {
@Lookup
protected abstract UserDao methodInject();
public void find(){
UserDao userDao = methodInject();
System.out.println("service="+this.hashCode());
System.out.println("dao="+ userDao.hashCode());
}
}