平時在用spring幫我們管理bean的時候,大部分情況下bean的scope都是singleton ,但是偶爾也會使用prototype,下面看這樣一種情況:
// connection 物件
@Configuration
@Scope("prototype")
public class Connection {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// connectionService
public class ConnectionService {
@Autowired
public Connection connection;
public Connection getConnection() {
return connection;
}
}
Test:
AnnotationConfigApplicationContext annotationConfigApplicationContext =
new AnnotationConfigApplicationContext(BeanConfig.class);
ConnectionService connectionService = annotationConfigApplicationContext.getBean(ConnectionService.class);
System.out.println(connectionService.getConnection()); // com.huzc.spring.ioc.autowired.Connection$$EnhancerBySpringCGLIB$$2e73c054@17f6480
System.out.println(connectionService.getConnection()); // com.huzc.spring.ioc.autowired.Connection$$EnhancerBySpringCGLIB$$2e73c054@17f6480
兩次獲取連接都為同一個,但是有時候這并非是我們需要的結果,我們可能需要的是兩次獲取的connection并非同一個,
這時我們可以使用spring提供的一個注解@Lookup來完成需求或者是實作ApplicationContextAware介面:
- Lookup方式
@Service
public abstract class ConnectionService {
@Lookup
public abstract Connection connection();
public Connection getConnection() {
return connection();
}
}
// 或者下面寫法
@Service
public class ConnectionService {
@Lookup
public Connection connection() {
return null;
};
public Connection getConnection() {
return connection();
}
}
- ApplicationContextAware
@Service
public class ConnectionService implements ApplicationContextAware {
private ApplicationContext applicationContext;
public Connection getConnection() {
return applicationContext.getBean(Connection.class);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/400541.html
標籤:java
上一篇:LeetCode - 430 - 扁平化多級雙向鏈表 - Java - 細喔
下一篇:Mybatis框架知識整理
