1. 程式人生 > >組合註解和元註解

組合註解和元註解

從 spring 2.0 開始為了響應 jdk1.5推出的註解功能, spring 開始大量加入註解來替代xml 配置.

元註解:即可註解到其他註解的註解.

組合註解:即被註解的註解.

示例:

組合註解:

package com.pangu.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

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

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@ComponentScan
public @interface CustomeConfiguration {
    
    String[] value() default {}; //覆蓋 value 引數.
    
}

service:

package com.pangu.annotation;

import org.springframework.stereotype.Service;

@Service
public class DemoService {

    public void outputResult(){
        System.out.println("從組合註解中照樣獲取 bean.");
    }
    
}

配置類(使用組合註解):

package com.pangu.annotation;

/**
 * @ClassName: DemoConfig
 * @Description: TODO 新的配置類
 * @author etfox
 * @date 2018年9月28日 下午11:45:19
 *
 * @Copyright: 2018 www.etfox.com Inc. All rights reserved.
 */
@CustomeConfiguration
public class DemoConfig {

}

測試:

package com.pangu.annotation;

import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    @Test
    public void test() {
        AnnotationConfigApplicationContext context = 
                new AnnotationConfigApplicationContext(DemoConfig.class);
        
        DemoService demoService = context.getBean(DemoService.class);
        
        demoService.outputResult();
        
        context.close();
        
    }

}

結果:

九月 28, 2018 11:46:36 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
資訊: Refreshing org.spring[email protected]75828a0f: startup date [Fri Sep 28 23:46:36 CST 2018]; root of context hierarchy
從組合註解中照樣獲取 bean.
九月 28, 2018 11:46:36 下午 org.springframework.context.support.AbstractApplicationContext doClose
資訊: Closing org.spring[email protected]75828a0f: startup date [Fri Sep 28 23:46:36 CST 2018]; root of context hierarchy