简介
将自己服务继承到spring容器中。
步骤
-
增加依赖包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
-
配置映射类
import org.springframework.boot.context.properties.ConfigurationProperties; /** * @Description * @Author luochaoqun * @Date 2020-08-24 08:20 **/ @ConfigurationProperties(prefix = "demo") public class DemoProperties { private String sayWhat; private String toWho; public String getSayWhat() { return sayWhat; } public void setSayWhat(String sayWhat) { this.sayWhat = sayWhat; } public String getToWho() { return toWho; } public void setToWho(String toWho) { this.toWho = toWho; }
}
- 读取配置。ConditionOnProperty会根据条件决定是否加载,这里会判断配置中isopen是否为true,如果为true才会去读取前缀为
demo的配置。定义想要集成到容器的bea。
import com.luochaoqun.ideas.frame.redis.starter.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
-
@Description
-
@Author luochaoqun
-
@Date 2020-08-24 08:26
**/
@Configuration
@EnableConfigurationProperties(DemoProperties.class)
@ConditionalOnProperty(prefix = "demo", name = "isopen", havingValue = "true")
public class DemoConfig {@Autowired
private DemoProperties demoProperties;@Bean
public DemoService demoService() {
return new DemoService(demoProperties.getSayWhat(), demoProperties.getToWho());
}
}
- 定义加载项,在resource下增加META-INFO文件夹,并增加spring.factories文件,项目启动的时候会去加载指定的类。
## starter 自动装配
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.luochaoqun.ideas.frame.redis.starter.config.DemoConfig
- 使用:引入自定义starter,然后通过@Resource引入依赖的Bean就可以调用了
网友评论