项目结构:
pom.xml
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.2.7.RELEASE</version>
<optional>true</optional>
</dependency>
UserProperties.java
@Data
@ConfigurationProperties(prefix = "com.run.user")
public class UserProperties {
private int id = 1;
private String name = "ych";
private String sex = "男";
}
UserService.java
public class UserService {
private UserProperties userProperties;
public UserService(UserProperties prop) {
this.userProperties = prop;
}
public void say() {
System.out.println(userProperties.toString());
}
}
UserServiceAutoConfiguration.java
@Configuration
@EnableConfigurationProperties(UserProperties.class)
public class UserServiceAutoConfiguration {
@Autowired
private UserProperties userProperties;
@Bean
@ConditionalOnMissingBean(UserService.class)
public UserService userService() {
UserService userService = new UserService(userProperties);
return userService;
}
}
spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration= com.run.UserServiceAutoConfiguration
原文:https://www.cnblogs.com/yinchh/p/13446312.html