我这里用一个小汽车类,通过导入自己模拟的包,来实现小汽车的对象实例化
一、war包工程结构(首先说明,我这是一个空的Maven项目开始的)
二、需要的xml配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
三、小汽车类
package cn.lyj.service;
public class CarService {
private String color; //小汽车颜色
private String carname; //小汽车牌子名字
public CarService(String color, String carname){
this.color=color;
this.carname=carname;
}
public String myCar(){
return "我的小汽车是"+this.color+"色的,它好像叫"+carname;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getCarname() {
return carname;
}
public void setCarname(String carname) {
this.carname = carname;
}
}
四、对应的给小汽车赋值的配置类
package cn.lyj.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix="car") //这里为了被引用时有对应的口令赋值
public class CarProperties {
private String color;
private String carname;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getCarname() {
return carname;
}
public void setCarname(String carname) {
this.carname = carname;
}
}
五、实现小汽车配置类
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;
import javax.annotation.Resource;
@Configuration
@ConditionalOnClass(CarService.class) //导入CarService,这个注解是为了实现创建单例的CarService
@EnableConfigurationProperties(CarProperties.class) //导入CarProperties配置类,该类是CarService的替身,帮助CarService在引用配置中拿值
public class CarAutoConfiguration {
@Resource
private CarProperties carProperties; //注入Car属性配置类
@Bean
@ConditionalOnMissingBean(CarService.class)
@ConditionalOnProperty(prefix="car",value="enabled",havingValue = "true") //设置“暗号”,等下引用赋值要用
public CarService carService(){
CarService carService = new CarService(carProperties.getColor(),carProperties.getCarname());
return carService;
}
}
六、别忘了在resources文件下创建META-INF(spring.factories)
org.springframework.boot.autoconfigure.EnableAutoConfiguration = \
cn.lyj.test.CarAutoConfiguration
七、打包
接下来就是新建个项目来引用了
一、向pom.xml自己写的依赖
<dependency>
<groupId>cn.lyj</groupId> <!--包路径-->
<artifactId>demo_fistconfig</artifactId> <!--小车类所在的工程名-->
<version>1.0-SNAPSHOT</version> <!--版本号-->
</dependency>
二、给小汽车赋值
三、测试(自己写个测试类)
@SpringBootTest
class DemoConfigApplicationTests {
@Autowired
CarService carService;
@Test
void contextLoads() {
System.out.println(carService.myCar());
}
}
测试结果
总结:不懂SpringBoot的自动装配原理就自己写一个吧!