ApplicationContextAwareインターフェースは、Springコンテキストをカプセル化します。コンテナー内のBeanを取得する必要がある場合、構成ファイルを手動で読み取り、オブジェクトを直接使用してBeanを取得する必要はありません。
テスト
Beanインスタンス
public interface SayHi {
public abstract String sayHi ();
}
@Component
public class HiBean implements SayHi {
@Override
public String sayHi() {
return "Hi";
}
}
@Component
public class HelloBean implements SayHi {
@Override
public String sayHi (){
return "hello";
}
}
コントローラーレイヤー
@RestController
public class SayHello {
@Autowired
private SayHelloService sayHelloService;
@RequestMapping("/hello1")
public Object sayHello1(){
return sayHelloService.say(true);
}
@RequestMapping("/hello2")
public Object sayHello2(){
return sayHelloService.say(false);
}
}
サービスレイヤー
@Service
public class SayHelloService {
public String say(boolean flag){
SayHi sayHi;
// 选择性的获取bean
if(flag) {
sayHi = (SayHi)AppUtil.getBean("helloBean");
} else {
sayHi = (SayHi)AppUtil.getBean("hiBean");
}
return sayHi.sayHi();
}
}
Apputil
@Component
public class AppUtil implements ApplicationContextAware {
private static ApplicationContext context;
public static Object getBean(String beanId) {
try{
return context.getBean(beanId);
}
catch(Exception ex){
// LOGGER.debug("getBean:" + beanId +"," + ex.getMessage());
System.out.println("error");
}
return null;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
}