-
Spring Framework 3.1 开始支持”@Enable 模块驱动“。所谓“模块”是指具备相同领域的功能组件集合,
组合所形成一个独立的单元。比如 Web MVC 模块、AspectJ代理模块、Caching(缓存)模块、JMX(Java 管
理扩展)模块、Async(异步处理)模块等。 -
自定义 @Enable 模块 基于注解驱动实现 - @EnableHelloWorld
-
实现自定义 @Enable模块驱动
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(HelloWorldImportSelector.class) // 自定义实现ImportSelector接口
public @interface EnableHelloWorld {}
自定义实现ImportSelector接口
public class HelloWorldImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{HelloWorldConfiguration.class.getName()};// 这里传来的数组是你要模块装配的类
}
}
定义javaBean
public class HelloWorldConfiguration {
@Bean
public String helloWorld() { // 方法名即 Bean 名称
return "Hello,World 2018";
}
}
以上就是自定以@Enable 模块装配的实现步骤 接下来在main方法里面运行既可
@EnableHelloWorld// 为自定义的模块注解,这一步会把自己实现的ImportSelector里面的javaBean,自动注入到容器中
public class EnableHelloWorldBootstrap {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(EnableHelloWorldBootstrap.class)
.web(WebApplicationType.NONE)
.run(args);
// helloWorld Bean 是否存在
String helloWorld =
context.getBean("helloWorld", String.class);
System.out.println("helloWorld Bean : " + helloWorld);
// 关闭上下文
context.close();
}
}