自定义注解通过spring获取Bean

Posted 不死码农

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义注解通过spring获取Bean相关的知识,希望对你有一定的参考价值。

自定义注解:

package com.example.demo.ann;

import org.springframework.stereotype.Repository;

import java.lang.annotation.*;

//注解运行的位置
@Target(ElementType.TYPE)
//运行的时机
@Retention(RetentionPolicy.RUNTIME)
//DOC
@Documented
@Repository
public @interface FirstRespoistory {
    String value() default "";
}

要获取的类:

package com.example.demo.ann;

@FirstRespoistory(value = "firstRe")
public class FirstReo {

    public void test(){
        System.out.println("ceshislaishi");
    }
}

获取方式:

package com.example.demo.ann;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan("com.example.demo.ann")
public class AnnoTest {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(AnnoTest.class).web(WebApplicationType.NONE).run(args);
        FirstReo firstRe = context.getBean("firstRe", FirstReo.class);
        firstRe.test();
        context.close();

    }
}

 

以上是关于自定义注解通过spring获取Bean的主要内容,如果未能解决你的问题,请参考以下文章

深入Spring 自定义注解加载和使用

如何获取spring 注解的bean

2) SpringBootApplication注解详解

Spring学习系列 通过Java代码装配Bean

通过Java代码装配Bean

210630:springBoot自动配置-自定义start