SpringBoot之自定义注解(基于BeanPostProcessor接口实现)

步骤

  • 使用@interface 自定义注解
  • 编写注解处理类,实现BeanPostProcessor接口

原理

实现BeanPostProcessor接口的类即为Bean后置处理器,Spring加载机制会在所有Bean初始化的时候遍历调用每个Bean后置处理器。
其顺序为:Bean实例化-》依赖注入-》Bean后置处理器-》@PostConstruct

缺陷

只有在会示例化成Bean的类中使用,注解才会生效。(因为是使用了Bean后置处理器实现的嘛)

代码示例

完整参考代码github

自定义注解接口

1
2
3
4
5
6
7
8
9
10
import org.springframework.stereotype.Component;
import java.lang.annotation.*;

@Target({ElementType.FIELD}) //声明应用在属性上
@Retention(RetentionPolicy.RUNTIME) //运行期生效
@Documented //Java Doc
@Component
public @interface Boy {
String value() default "";
}

注解处理类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component //注意:Bean后置处理器本身也是一个Bean
public class BoyAnnotationBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
/**
* 利用Java反射机制注入属性
*/
Field[] declaredFields = bean.getClass().getDeclaredFields();
for (Field declaredField : declaredFields) {
Boy annotation = declaredField.getAnnotation(Boy.class);
if (null == annotation) {
continue;
}
declaredField.setAccessible(true);
try {
declaredField.set(bean, annotation.value());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return bean;
}

@Override
public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
return o; //这里要返回o,不然启动时会报错
}
}

注解使用类

1
2
3
4
5
6
7
8
9
10
11
12
13
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;

@Service
public class HelloBoy {

@Boy("小明")
String name = "world";

public void sayHello() {
System.out.println("hello, " + name);
}
}

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import com.markey.annotations.Boy.HelloBoy;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloBoyTest {

@Autowired
HelloBoy helloBoy;

@Test
public void HelloBoyTest() {
helloBoy.sayHello();
}

}

运行结果

注解无效示例

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import com.markey.annotations.Boy.HelloBoy;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloBoyTest {

HelloBoy helloBoy = new HelloBoy(); //新建的对象,不是容器中的Bean
@Test
public void HelloBoyTest() {
helloBoy.sayHello();
}
}

运行结果

Tips
其实Spring很多原生注解(例如@Autowired,其处理类是AutowiredAnnotationBeanPostProcessor),也是通过实现BeanPostProcessor接口这种方式来实现的。