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(); } }