Spring組合註解和元註解

元註解:能夠註解到其餘註解的註解。java

組合註解:被註解的註解,組合註解具有元註解的功能。spring

@Configuration就是一個組合@Compoent註解code

 

組合註解示例ip

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.lang.annotation.*;

/**
 * @author Kevin
 * @description
 * @date 2016/7/1
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
// 組合@Configuration註解
@Configuration
// 組合@ComponentScan註解
@ComponentScan
public @interface WiselyConfiguration {
    // 覆蓋@ComponentScan value參數
    String[] value() default {};
}

示例Bean類get

import org.springframework.stereotype.Component;

/**
 * @author Kevin
 * @description
 * @date 2016/7/1
 */
@Component
public class DemoService {
    public void printResult() {
        System.out.println("從組合註解配置中獲取的Bean");
    }
}

配置類io

/**
 * @author Kevin
 * @description
 * @date 2016/7/1
 */
@WiselyConfiguration("ch03.anno")
public class DemoConfig {
}

運行class

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author Kevin
 * @description
 * @date 2016/7/1
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class);
        DemoService demoService = context.getBean(DemoService.class);
        demoService.printResult();
        context.close();
    }
}
相關文章
相關標籤/搜索