自定义的组合注解代码如下
package com.springboot.Config; //注意包的路径 这个是重点
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//扫描目录 superconfig 自定的注解因为有其他的注解在一起 所以叫做组合注解 自定义注解上的注解叫做元注解
public @interface SuperCombinationConfig {
//接下来就是覆盖参数 因为注解里面的参数都是不一样的所以要重新覆盖
String[] value() default {};
}
我是使用的java配置代替了xml配置 引用我刚才自定义的组合
package com.springboot.Test;//配置主文件包路径
import com.springboot.Config.SuperCombinationConfig;
@SuperCombinationConfig("com.springboot.Test")//扫描的路径
public class CombinationConfig {
}
定义一个测试的service方法证明组合注解是可以扫描到的
package com.springboot.Test;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
public void inputout() {
System.out.println("组合注解");
}
}
使用mai方法进行测试
package com.springboot.Config;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.springboot.Test.CombinationConfig;
import com.springboot.Test.DemoService;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CombinationConfig.class);
DemoService bean = context.getBean(DemoService.class);
bean.inputout();
context.close();
}
}
测试结果
八月 16, 2018 2:39:02 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Thu Aug 16 14:39:02 CST 2018]; root of context hierarchy
组合注解
八月 16, 2018 2:39:02 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Thu Aug 16 14:39:02 CST 2018]; root of context hierarchy
由于之前对于组合注解不太熟悉导致报错,原因是因为没有将service和@SuperCombinationConfig扫描,最后才发现自定义的组合注解,spring必须扫描到才能执行。