SpringBoot的ApplicationContextAware

springboot启动时,扫描生成的对象会放在springboot容器中被管理,不过有时候我们在程序中需要通过类名,或者对象名,来获取到所需要使用的对象,这种情况我们就可以使用ApplicationContextAware来实现

示例:

package com.qingnian.spring.running;


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class AwareClass implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("类被创建时自动执行");
        this.applicationContext=applicationContext;
    }

    //通过name获取Bean
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    //通过class获取Bean
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name, Class<T> clazz) {
        return applicationContext.getBean(name, clazz);
    }
}

做个简单的小例子,改变Controller层自动注入的servide对象,从上下文获取

@Controller("good")
@Slf4j
public class GoodController {

    @Autowired
    private GoodService goodService;

    @GetMapping("/getInfo/{id}")
    @ResponseBody
    public Good getOneInfo(@PathVariable Long id){
        return goodService.selectOne(id);
    }

}

改变后:

@Controller("good")
@Slf4j
public class GoodController implements ApplicationContextAware {

    /*@Autowired
    private GoodService goodService;*/

    private static ApplicationContext applicationContext;

    //通过name获取Bean
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("自动执行");
        this.applicationContext=applicationContext;

    }
    
    @GetMapping("/getInfo/{id}")
    @ResponseBody
    public Good getOneInfo(@PathVariable Long id){
        //通过对象名获取到这个接口对象
        GoodService goodService = (GoodService)getBean("goodServiceImpl");
        return goodService.selectOne(id);
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值