@component注解和@bean,spring boot: 組合注解與元注解

 2023-12-06 阅读 29 评论 0

摘要:package ch2.annotation;//target/elementType用來設定注解的使用范圍 import java.lang.annotation.ElementType; import java.lang.annotation.Target;//表明這個注解documented會被javac工具記錄 import java.lang.annotation.Documented;//retention/retentionPolicy(保留
package ch2.annotation;//target/elementType用來設定注解的使用范圍
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;//表明這個注解documented會被javac工具記錄
import java.lang.annotation.Documented;//retention/retentionPolicy(保留)注解,在編譯的時候會被保留在某個(那個)特定的編譯階段
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;//target/elementType用來設定注解的使用范圍:type用于類或接口上
@Target(ElementType.TYPE)//retention/retentionPolicy(保留)注解,在編譯的時候會被保留在某個(那個)特定的編譯階段
//這種類型的Annotations將被JVM保留
@Retention(RetentionPolicy.RUNTIME)//表明這個注解@documented會被javac工具記錄
@Documented//組合注解
//組合configuration元注解
@Configuration
//組合ComponentScan元注解
@ComponentScan//組合注解
public @interface WiselyConfiguration {//覆蓋value參數String[] value() default{};}

  

package ch2.annotation;import org.springframework.stereotype.Service;//聲明為spring的組件
@Service//演示服務Bean
public class DemoService {public void outputResult(){System.out.println("從組合注解配置里,照樣獲得Bean");}}

  

package ch2.annotation;//引入ch2.annotation下的包
//使用wiselyConfiguration組合注解代替@ComponentScan,@Configuration
@WiselyConfiguration("ch2.annotation")//新的配置類
public class DemoConfig {}

  

?

package ch2.annotation;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {public static void main(String[] args){AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class);DemoService demoService = context.getBean(DemoService.class);demoService.outputResult();context.close();}}

  

@component注解和@bean?轉載于:https://www.cnblogs.com/achengmu/p/8276034.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/191352.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息