一、afterPropertiesSet作用
在Spring中,我们经常会使用到afterPropertiesSet这个方法,它属于InitializingBean接口,在Bean初始化之后执行。其主要作用是对Bean的属性进行校验和初始化。在Spring中,对于Bean的属性,通常会配合注解或者xml配置方式进行注入或者赋值,而且属性赋值或注入是在对象实例化之后进行的,所以我们无法在构造方法中进行对Bean属性值的校验。afterPropertiesSet就是解决了这个问题,它提供了一个回调方法,让我们在Bean属性赋值后对值进行校验和初始化。
二、afterPropertiesSet方法作用
在Spring中,afterPropertiesSet是一个被回调的方法,也是Bean初始化之后进行校验和初始化的方法。当Bean的属性属性值赋完之后,Spring会自动调用该方法,从而完成属性值的校验和初始化。和自定义方法不同的是,afterPropertiesSet方法可以在Bean对象被使用前,自动对Bean对象的属性对其进行初始化操作。这是因为该方法是在Bean实例化后,所有属性值赋值之后,其他初始化操作之前调用的。
三、afterPropertiesSet方法
afterPropertiesSet方法需要实现InitializingBean接口,需要在类中重写该方法,实现初始化的操作。
<bean id="redisClient" class="com.xxx.RedisClient" init-method="init"> <property name="host" value="localhost"/> <property name="port" value="6379"/> <property name="password" value="password"/> </bean> public class RedisClient implements InitializingBean{ private String host; private int port; private String password; private Jedis jedis; //初始化方法 public void init() { jedis = new Jedis(host,port); jedis.auth(password); } //重写afterPropertiesSet方法 @Override public void afterPropertiesSet() throws Exception { if (StringUtils.isEmpty(host)) { throw new IllegalArgumentException("host property not set!"); } if (port <= 0) { throw new IllegalArgumentException("port property not set!"); } } //getter/setter省略 }
四、afterPropertiesSet不执行
如果在Spring XML文件中没有配置BeanPostProcessor进行对Bean进行代理,那么afterPropertiesSet方法就不会被执行。此外,还有一种情况,就是Bean中没有实现InitializingBean接口,也就是没有afterPropertiesSet方法,那么也会导致此方法不会被执行。
五、afterPropertiesSet执行顺序
在一个Bean消费的时候,Spring管理的Bean中所有的属性,都会在Bean的构造方法调用之后进行赋值,然后最后执行afterPropertiesSet回调方法进行Bean的初始化。具体顺序如下:
- 1、实例化Bean对象
- 2、设置Bean对象的属性
- 3、检测是否实现了BeanPostProcessor接口,如果实现了,进行后置处理
- 4、检测是否实现了InitializingBean接口,如果实现了,则调用afterPropertiesSet方法
- 5、BeanPostProcessor接口postProcessBeforeInitialization方法
- 6、调用默认的init-method方法
- 7、BeanPostProcessor接口postProcessAfterInitialization方法
六、afterPropertiesSet方法执行顺序
如果一个类实现了多个BeanPostProcessor后置处理接口以及InitializingBean接口,那么它们的执行顺序发生以下变化:
1、多个BeanPostProcessor接口的实现类的先后顺序不确定。
2、BeanPostProcessor接口的实现类的postProcessBeforeInitialization方法会在InitializingBean接口的afterPropertiesSet方法之前执行,postProcessAfterInitialization方法会在afterPropertiesSet方法之后执行。
七、afterPropertiesSet会执行多少遍
afterPropertiesSet方法仅在Bean初始化之后执行,因此它只会执行一次。
八、afterPropertiesSet和Autowired
在Spring中,容器在自动注入之后会调用afterPropertiesSet方法,因此我们可以在afterPropertiesSet方法中处理注入的依赖项。如下我们来看个例子:
@Component public class ExampleBean implements InitializingBean{ private SomeService someService; @Autowired public void setSomeService(SomeService someService) { this.someService = someService; } //重写afterPropertiesSet方法 @Override public void afterPropertiesSet() throws Exception { if (this.someService == null) { throw new IllegalArgumentException("someService property null!"); } } //其他方法省略 }
在上述代码中,如果someService依赖项未正确注入,将抛出异常,从而保证了Bean初始化的必要条件。
原创文章,作者:RUKWQ,如若转载,请注明出处:https://www.506064.com/n/324737.html