立即学习:https://edu.csdn.net/course/play/25330/298883?utm_source=blogtoedu
1. @ImportResource
Spring Boot自动装配/自动配置
Spring等配置文件 默认会被Spring Boot自动给配置好
如果要自己编写Spring等配置文件,SPring Boot能否识别?手写一个spring.xml试验一下。结果:默认不识别,如需识别需要使用该注解指定;用法:@ImportResource(locations={"class:spring.xml"});放在启动类前使用;但不推荐手写spring配置文件。通过注解配置,这也是SpringBoot的核心思想;大致的配置方向:
写配置类:
建一个config包:@Configuration @Bean
示例:
//配置类(等价于spring.xml)
@Configuration
public class AppConfig{//<bean if="xxxxxxx">
@Bean
public StudentService stuService(){
StudentService stuService = new StudentService();
StudentDao stuDao = new StudentDao();
stuService.setStudentDao(stuDao);
return stuService;//返回值<bean cleass="xxxxxx">
}
}
2. SpringBoot全局配置文件中的 占位符表达式
a.随机数 ${random.uuid/lon/int}等
b.引用变量值
yml中:
student:
uname: x
name: ${student.user.name}
实际引用的是properties中的student.user.name的值
student:
uname: x
name: ${student.user.name2:defaultvalue}
如果roperties中的student.user.name2不存在则使用默认值
c.配置与注解的体现
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="${jdbc.url}"/>
</bean>
等价于
@Configuration
@ImportResource("classpath:/com/acme/properties-config.xml")
public class AppConfig {
@Value("${jdbc.url}")
private String url;
}