${key}从环境变量、配置文件当中获取值

@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person") @Validated public class Person { /** * <bean class="Person"> * <property name="lastName" value="字面量/${key}从环境变量、配置文件当中获取值/#{SpEL}"></property> * </bean> * * <bean>是组件加入到容器中, * * @Component也是将组件,加入到容器中。 */ // @Value("${person.last-name}") //@Email private String lastName; // @Value("#{11*2}") private Integer age; //@Value("true") private Boolean boss; private Date birth; private Map<String,Object> maps; private List<Object> lists; private Dog dog; 

@ImportResource : 导入Spring的配置文件,让配置文件里面的内容生效;

springboot里面没有spring的配置文件,我们自己编写的配置文件,也不能够自动识别。

如果是想让我们的spring配置文件生效,

加载@ImportResource注解,标注在主配置类上,能够让我们来加载多个spring的配置文件。

@ImportResource(locations = {"classpath:beans.xml"})

导入spring的配置文件,让其生效

然而,在开发的过程当中,我们不可能给容器当中添加组件,要写个配置文件,

然后通过@ImportResource(locations = {"classpath:beans.xml"})把配置文件导入进来。

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="helloService" class="com.atguigu.springboot.service.HelloService"> </bean> </beans> 

上面的这种方式,已经不推荐了。

springboot推荐的给容器中添加组件的方式是:

首先写一个配置类,类似于,我们刚才写的配置文件一样。

然后,使用@Bean给容器中添加组件。

/**
 * @Configuration 指明当前类,是一个配置类,就是替代之前的spring的配置文件
 *
 * 以前在配置文件当中,用bean标签,添加组件的。
 *
 * 在配置类当中,通过
 */
@Configuration
public class MyAppConfig { //将方法的返回值,添加到容器中;容器中,这个组件默认的id就是方法名 @Bean public HelloService helloService(){ System.out.println("配置类@Bean给容器中,添加组件了"); return new HelloService(); }

这么好的网站 https://www.jianshu.com/p/279bc722dfd3
这么好的网站 https://www.jianshu.com/p/4ab5a0b491e6
 这么好的网站 https://www.jianshu.com/p/91eaf817b6a3
这么好的网站 https://www.jianshu.com/p/584b22212f24
这么好的网站 https://www.jianshu.com/p/71f7f290423f

扫描二维码关注公众号,回复: 11141137 查看本文章

猜你喜欢

转载自www.cnblogs.com/3115765473-----QQ/p/12791465.html