- @Component/Service/Controller:管理bean
- @Scope:bean范围,可以指定单例,多例,session,request,也可以指定动态代理模式。
@Component
@Scope(value = DefaultListableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ScopeProxyBean {
public void test(){
System.out.println("aaaa");
}
}
- @Conditional:定义类实现Conditional接口,bean被spring管理条件
public class MyCondition implements Condition {
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment env = context.getEnvironment();
String system = env.getProperty("os.name");
System.out.println("系统环境为 ==="+system);
// 系统环境在Windows才加载该bean到容器中
if(system.contains("Windows")){
return false;
}
return true;
}
}
@Component
@Conditional(MyCondition.class)
public class TestCondition {
}
- @AliasFor
- @PropertySources与PropertySource
@Configuration
@ComponentScan(basePackages = {"com.example.demo.bean"})
//@Conditional(MyCondition.class)
@PropertySource("classpath:application.properties")
public class MainConfig {
@Bean(autowire = Autowire.BY_NAME)
public AwareBean awareBean(){
return new AwareBean();
}
@Component
class TestMainConfig{
}
}
@Component
//@Conditional(MyCondition.class)
public class TestCondition {
@Value("${server.port}")
private String port;
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
}
- @Import/ImportSelector/DeferredImportSelector与ImportAware
ImportAware:获取注解上的值,作用参考EnableAsync注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(ProxyConfig.class)
public @interface ImportTest {
String importTest() default "";
}
@Component
public class ProxyConfig implements ImportAware {
AnnotationAttributes annotationAttributes;
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
annotationAttributes = AnnotationAttributes.fromMap(importMetadata.getAnnotationAttributes(ImportTest.class.getName()));
System.out.println("=====" + annotationAttributes.getString("importTest"));
}
}
Import与ImportSelector/DeferredImportSelector,可以导入bean,实现DeferredImportSelector有延迟效果。
public class ImportSelectorTest implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
System.out.println("ImportSelectorTest");
return new String[]{"com.example.demo.bean.importAware.test1"};
}
}
public class DeferredImportSelectorTest implements DeferredImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
System.out.println("DeferredImportSelectorTest");
return new String[]{"com.example.demo.bean.importAware.test2"};
}
}
// 启动类添加@Import({ImportSelectorTest.class, DeferredImportSelectorTest.class})
@DependsOn
@Component
@DependsOn({"dependB"})
public class DependA {
@Autowired
private DependB dependB;
}