自定義注解通過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();

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM