自动装配

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 配置的条件比较单一。

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值