一、模式注解与装配
用于声明类在应用中的角色。举例如下:
注解 | 说明 |
---|---|
@Component | 通用注解,声明一个普通bean |
@Controller | 声明web层角色 |
@Service | 声明服务层角色 |
@Repository | 声明dao层数据仓储角色 |
@Configuration | 声明配置类 |
添加模式注解的类如何进行装配?有xml和注解两种方法:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--注解支持-->
<context:annotation-config />
<!--扫描包范围-->
<context:component-scan base-package="com.xx" />
</beans>
@Configuration
@ComponentScan(basePackages = "com.xx")
public class springConfig {
}
二、@Enable模块装配
指一系列具有相同领域功能的组件集合。 举例如下:
模块注解 | 功能说明 |
---|---|
@EnableWebMvc | web mvc模块 |
@EnableTransactionManagement | 事务管理模块 |
@EnableCaching | 缓存模块 |
@EnableAsync | 异步模块 |
@EnableMBeanExport | JMX模块 |
@enable*注解如何使用,我们参考@EnableAsync源码实现看一下
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({AsyncConfigurationSelector.class})
public @interface EnableAsync {
中间代码......
}
public class AsyncConfigurationSelector extends AdviceModeImportSelector<EnableAsync> {
private static final String ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME = "org.springframework.scheduling.aspectj.AspectJAsyncConfiguration";
public AsyncConfigurationSelector() {}
public String[] selectImports(AdviceMode adviceMode) {
中间代码......
}
}
public abstract class AdviceModeImportSelector<A extends Annotation> implements ImportSelector {
中间代码......
}
public interface ImportSelector {
String[] selectImports(AnnotationMetadata var1);
}
通过以上代码得知,关键是通过实现ImportSelector接口来实现的。下面模仿源码自定义一个@Ebable模块。
public class Hello1 {
}
public class Hello2 {
}
public class EnableHello implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
return new String[]{Hello1.class.getName()};
}
}
@SpringBootApplication
@Import(EnableHello.class)
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
System.out.println(context.getBean(Hello1.class));
System.out.println(context.getBean(Hello2.class));
}
}