版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29689487/article/details/82891681
从 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.springframework.context.annotation.AnnotationConfigApplicationContext@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.springframework.context.annotation.AnnotationConfigApplicationContext@75828a0f: startup date [Fri Sep 28 23:46:36 CST 2018]; root of context hierarchy