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

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot中,可以通过以下步骤来自定义注解: 1. 定义注解:使用Java注解语法定义一个注解,可以设置注解的属性和默认值。 2. 创建解析器:创建一个解析器类,用于解析注解并执行相应的操作。 3. 注册解析器:在SpringBoot的配置类中注册解析器,使其能够被SpringBoot自动扫描到并执行。 具体实现步骤可以参考以下内容: 1. 定义注解: ```java @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { String value() default ""; } ``` 2. 创建解析器: ```java @Component public class MyAnnotationParser implements ApplicationContextAware { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public void parse(Object object) { Class<?> clazz = object.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { MyAnnotation annotation = field.getAnnotation(MyAnnotation.class); if (annotation != null) { String value = annotation.value(); Object bean = applicationContext.getBean(value); field.setAccessible(true); try { field.set(object, bean); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } } ``` 3. 注册解析器: ```java @Configuration public class MyConfiguration { @Autowired private MyAnnotationParser myAnnotationParser; @Bean public static BeanPostProcessor beanPostProcessor() { return new BeanPostProcessor() { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { myAnnotationParser.parse(bean); return bean; } }; } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值