springboot公共包封裝-公共包自動注入的2種方式

springboot公共包封裝-公共包自動注入的2種方式

spring boot封裝公共包時,有兩種牀用的公共方法自動注入bean容器的方式。

1. 配置META-INF

在resources目錄下添加META-INF目錄,添加文件spring.factories文件:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.yc.requestlog.RequestLogConfiguration

這樣spring啓動時就會自動加載RequestLogConfiguration類,我們可以在類中手動注入bean。

@Configuration
@EnableConfigurationProperties(RequestLogProperties.class)
public class RequestLogConfiguration {

    @Bean
    public LogTraceRepository logTraceRepository() {
        return new LogTraceRepository();
    }
}

2. 自定義啓動註解方式

自定義一個啓動註解,手動添加註解到spring項目的main函數上:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Configuration
@Import({CustomProperties.class,
    CustomBeanRegistrar.class})
public @interface EnableCustomComponent {

}
@Data
public class CustomProperties {
    @Value("${spring.redis.port:1111}")
    private int port;
}
public class CustomBeanRegistrar {

    @Bean
    public TestService testService() {
        return new TestService();
    }
}

在springboot項目中就可以正常引用。

@Resource
private TestService testService;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章