-
新建maven工程yahang-spring-boot-starter (starter是一个空JAR包,仅仅作为maven下载jar包的启动器)
-
新建maven工程yahang-spring-boot-starter-autoconfigure (实际工作的模块)
-
yahang-spring-boot-starter作为一个启动器,设置依赖于yahang-spring-boot-starter-autoconfigure
-
<dependency><groupId>com.njupt</groupId><artifactId>yahang-spring-boot-starter-autoconfigure</artifactId><version>0.0.1-SNAPSHOT</version></dependency>
-
yahang-spring-boot-starter-autoconfigure模块下,设置依赖于spring-boot-starter
-
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><version>2.3.0.RELEASE</version></dependency>
-
yahang-spring-boot-starter-autoconfigure模块下,新建包com.njupt,然后新建一个实体类,该实体类为要配置为bean的类
-
public class MyDataSource {
-
public String url;
-
public String username;
-
public String password;
-
public MyDataSource(String url, String username, String password) {
-
super();
-
this.url = url;
-
this.username = username;
-
this.password = password;
-
}
-
}
-
-
yahang-spring-boot-starter-autoconfigure模块下的com.njupt包下,然后新建一个MyDataSourceProperties类,该实体类为读取yml文件的类,并设置getter,setter方法。
-
@ConfigurationProperties(prefix = "yahang.mydatasource")
-
public class MyDataSourceProperties {
-
private String url;
-
private String username;
-
private String password;
-
-
yahang-spring-boot-starter-autoconfigure模块下的com.njupt包下,然后新建一个MyDataSourceAutoConfigure类,该类使用MyDataSourceProperties对象的属性,new MyDataSource对象,并注入为Bean
-
@Configuration
-
@ConditionalOnWebApplication
-
@EnableConfigurationProperties(MyDataSourceProperties.class)
-
public class MyDataSourceAutoConfigure {
-
-
@Autowired
-
private MyDataSourceProperties myDataSourceProperties;
-
-
@Bean
-
public MyDataSource getDataSource() {
-
String url=myDataSourceProperties.getUrl();
-
String username=myDataSourceProperties.getUsername();
-
String password=myDataSourceProperties.getPassword();
-
return new MyDataSource(url, username, password);
-
}
-
}
-
-
为了让Springboot加载MyDataSourceAutoConfigure,需要在resources目录下新建META-INF/spring.factories
-
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
-
com.njupt.MyDataSourceAutoConfigure
-
-
使用maven install 安装autoconfigure和starter模块。
-
测试
-
新建Springboot的web应用,pom文件引入自定义的starter
-
<dependency><groupId>com.njupt</groupId><artifactId>yahang-spring-boot-starter</artifactId><version>0.0.1-SNAPSHOT</version></dependency>
-
编写application.yml
-
yahang:
-
mydatasource:
-
url: localhaost
-
username: yahang
-
password: 123456
-
-
编写测试代码
-
@Controller
-
public class MyController {
-
-
@Autowired
-
private MyDataSource dataSource;
-
@ResponseBody
-
@RequestMapping("/test")
-
public String getDatasource() {
-
return dataSource.url+" : "+ dataSource.username+" : "+dataSource.password;
-
}
-
}
-
-
测试
-
-
1.自定义启动器starter
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.