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

17 篇文章 0 订阅
11 篇文章 0 订阅

步骤

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

原理

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

缺陷

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

代码示例

完整参考代码github

自定义注解接口

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

注解处理类

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,不然启动时会报错
    }
}

注解使用类

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

测试类

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();
    }

}

运行结果

注解无效示例

测试类

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接口这种方式来实现的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值