SpringBoot基础篇(三)ApplicationContextAware和CommandLineRunner接口

1.ApplicationContextAware接口

        ApplicationContext对象是Spring开源框架的上下文对象实例,在项目运行时自动装载Handler内的所有信息到内存。基于SpringBoot平台完成ApplicationContext对象的获取,并通过实例手动获取Spring管理的bean。

ApplicationContextAware接口的方式获取ApplicationContext对象实例,但并不是SpringBoot特有的功能,早在Spring3.0x版本之后就存在了这个接口,在传统的Spring项目内同样是可以获取到ApplicationContext实例的。

/**
 * Spring的ApplicationContext的持有者,可以用静态方法的方式获取spring容器中的bean
 *@Component不能去掉,否则无法调用setApplicationContext方法
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {
	/**
	 * 上下文对象实例
	 */
	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextHolder.applicationContext = applicationContext;
	}
/**
 * 获取application上下文对象
 * @return
 */
	public static ApplicationContext getApplicationContext() {
		assertApplicationContext();
		return applicationContext;
	}

	/**
	 * 通过name获取bean
	 * @param beanName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String beanName) {
		assertApplicationContext();
		return (T) applicationContext.getBean(beanName);
	}

	/**
	 * 通过class获取bean
	 * @param requiredType
	 * @return
	 */
	public static <T> T getBean(Class<T> requiredType) {
		assertApplicationContext();
		return applicationContext.getBean(requiredType);
	}

	private static void assertApplicationContext() {
		if (SpringContextHolder.applicationContext == null) {
			throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");
		}
	}

}

 【上述代码注意实现】(1)ApplicationContextProvider类上的@Component注解是不可以去掉的,去掉后Spring就不会自动调用setApplicationContext方法来为我们设置上下文实例。

(2)我们把SpringContextHolder作为工具类,使用SpringContextHolder.getBean()方式直接调用获取。

2.CommandLineRunner接口

     在实际应用中,我们会在项目服务启动的时候就去加载一些数据或者做一些事情这样的需求。为了解决这个问题,springboot为我们提供了一个方法,通过实现接口CommandLineRunner来实现。

**
 * 服务器启动时执行
 */
@Component
public class MyStartRunning implements CommandLineRunner
{
    @Autowired
    private IDeptService deptService;
    @Override
    public void run(String... args) throws Exception
    {
        System.out.println("============服务器启动时执行================");
        for (String arg:args){
            //args参数数组是启动传入进来的
            System.out.println("========执行的参数====="+arg);
        }
        Dept dept = deptService.selectById(25);
        System.out.println("=======dept:======="+dept.toString());
    }
}

 

 

 

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Spring Boot中,你可以通过实现`FactoryBean`、`ApplicationContextAware`和`InitializingBean`接口来自定义Bean的创建和初始化过程。 首先,让我们看看如何实现`FactoryBean`接口: ```java import org.springframework.beans.factory.FactoryBean; public class MyFactoryBean implements FactoryBean<MyBean> { @Override public MyBean getObject() throws Exception { // 创建并返回自定义的Bean对象 return new MyBean(); } @Override public Class<?> getObjectType() { return MyBean.class; } @Override public boolean isSingleton() { return true; // 返回true表示该Bean是单例的 } } ``` 在上面的示例中,`MyFactoryBean`类实现了`FactoryBean`接口,并重写了`getObject()`、`getObjectType()`和`isSingleton()`方法。通过实现这些方法,你可以定义自己的逻辑来创建和配置Bean。 接下来,让我们看看如何实现`ApplicationContextAware`接口: ```java import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContext; public class MyApplicationContextAware implements ApplicationContextAware { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } // 可以在这里使用applicationContext访问其他Bean或执行其他操作 } ``` 在上面的示例中,`MyApplicationContextAware`类实现了`ApplicationContextAware`接口,并重写了`setApplicationContext()`方法。通过重写该方法,你可以在Bean初始化时获得`ApplicationContext`对象,并在需要时使用它。 最后,让我们看看如何实现`InitializingBean`接口: ```java import org.springframework.beans.factory.InitializingBean; public class MyInitializingBean implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { // 在这里执行Bean的初始化逻辑 } } ``` 在上面的示例中,`MyInitializingBean`类实现了`InitializingBean`接口,并重写了`afterPropertiesSet()`方法。在该方法中,你可以实现自定义的Bean初始化逻辑。 请注意,以上示例中的类都是自定义的类,你需要将它们注册为Spring Bean,可以使用`@Component`注解或在配置类中进行配置。例如,在配置类中添加如下代码: ```java @Configuration public class AppConfig { @Bean public MyFactoryBean myFactoryBean() { return new MyFactoryBean(); } @Bean public MyApplicationContextAware myApplicationContextAware() { return new MyApplicationContextAware(); } @Bean public MyInitializingBean myInitializingBean() { return new MyInitializingBean(); } } ``` 通过以上配置,你可以将自定义的FactoryBean、ApplicationContextAware和InitializingBean注册为Spring Bean,并在应用中使用它们。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值