需要依赖spring-boot-starter。因为需要用到springboot的注解。
3、准备需要注入的beansprintboot02 org.example 1.0-SNAPSHOT 4.0.0 mydruid-spring-boot-starter org.springframework.boot spring-boot-starter org.projectlombok lombok 1.18.24
@Data
public class DataSource {
private String driver;
private String url;
private String username;
private String password;
}
4、准备配置类
@Configuration
public class AppConfig {
@Bean
@ConditionalOnMissingBean
@ConfigurationProperties(prefix = "config.datasource")
public DataSource getDataSource(){
return new DataSource();
}
}
@Conditional注解的所有类型:
5、创建META-IFO文件夹,开启自动扫描
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.xycf.common.config.AppConfig
6、打包
8、配置yml文件sprintboot02 org.example 1.0-SNAPSHOT 4.0.0 springboot02-child org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test org.example mydruid-spring-boot-starter 1.0-SNAPSHOT
@ConfigurationProperties(prefix=“xxx”)会读取文件中以xxx为前缀的所有值并注入到实体bean中
config:
datasource:
driver: 111
url: 222
username: 333
password: 444
9、编写测试类
package com.xycf.springboot;
import com.xycf.common.entity.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = SpringbootApplication.class)
@RunWith(SpringRunner.class)
public class SpringbootApplicationTest {
@Autowired
private DataSource dataSource;
@Test
public void test(){
System.out.println(dataSource);
}
}
结果如下



