参考文章:SpringBoot自定义starter_springboot3.0自定义starter_kksilu的博客-CSDN博客
我这里是根据上面博主的文章做的练习
DemoService:
package com.gc;
public class DemoService {
private String demo;
public DemoService(String demo){
this.demo = demo;
}
@Override
public String toString() {
return "DemoService{" +
"demo='" + demo + '\'' +
'}';
}
}
DemoConfig:
package com.gc;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "hh")
public class DemoConfig {
private String demo;
@Bean
public DemoService demoService(){
return new DemoService(demo);
}
public String getDemo() {
return demo;
}
public void setDemo(String demo) {
this.demo = demo;
}
}
Spring.factories:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.gc.DemoConfig
安装到maven仓库
在application.properties中添加配置:
hh.demo=123
启动类测试:
package com.gc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class UserApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(UserApplication.class, args);
DemoService demoservice = context.getBean("demoService", DemoService.class);
System.out.println(demoservice);
}
}
最后就可以看到,控制台输出 DemoService{demo='123'} 了!!!