Spring 模式注解:
装配方式
自定义模式注解
使用:
@FirstlevelRepository(value = "myFirstRepository")
public class MyFirstRepository {
}
主类:
@ComponentScan(basePackages = "com.Repository")
public class FirstRepositoryBootstrap {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(FirstRepositoryBootstrap.class)
.web(WebApplicationType.NONE)
.run(args);
MyFirstRepository myFirstRepository = context.getBean("myFirstRepository",MyFirstRepository.class);
System.out.println(myFirstRepository);
//关闭上下文
context.close();
}
@SpringBootApplication 注解就使用了这种特性
实现方式
注解驱动方式 自定义@Enable 模块
自定义Configuration 类。
@Configuration
public class HelloWorldConfiguration {
//方法名就是 bean 的名字
@Bean
public String helloWorld(){
return "hello,world";
}
}
自定义@Enable 模块注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(HelloWorldConfiguration.class)
public @interface EnableHelloWorld {
}
主类测试:
@EnableHelloWorld
public class EnableHelloworldBootstrap {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(EnableHelloworldBootstrap.class)
.web(WebApplicationType.NONE)
.run(args);
String str = context.getBean("helloWorld",String.class);
System.out.println(str);
//关闭上下文
context.close();
}
}
接口编程方式 自定义@Enable 模块
创建 实现ImportSelector 接口的类。
public class HelloWorldImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
//我们就直接返回HelloConfiguration,就可以获取到 配置类中的bean
return new String[]{HelloWorldConfiguration.class.getName()};
}
}
@Enable 修改为
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(HelloWorldImportSelector.class)
public @interface EnableHelloWorld {
}
还可用上面的主类进行测试。
这种方式比第一种方式更间接。
我们可以在HelloWorldImportSelector 添加分支或者条件判断。所以这种方式更弹性。
定义接口
创建不同实现类。
测试主类
@Profile 配置的条件比较单一。