使用ApplicationContextAware优雅地获取bean对象

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";
    }
}

controller层

@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层

@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;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41948178/article/details/112609971