5.注解

1.@PropertySource:加载指定路径的配置文件

用法:意思是加载person.properties配置文件中的值,并进行绑定
@PropertySource("classpath:person.properties")
@Component
//@ConfigurationProperties(prefix = "person")---->加载全局配置文件的值
public class Person {
    ...
}
新建一个person.properties文件:
     person.name=吴孟达
    person.age=18
    person.birth=1992/06/06
    person.map.k1=v1
    person.map.k2=v2
    person.list=a,b,c
    person.dog.name=刘丹
    person.dog.age=18
    PERSON_PARENT_NAME=吴孟达父

2.@ImportResource:导入spring的配置文件,让配置里面的内容生效

如果想要spring的配置文件生效,加载进来,@ImportResource标注在一个配置类上!

springboot的启动类:
        @SpringBootApplication
        @ImportResource("classpath:bean.xml")------>导入指定的spring配置文件,并使其生效!如果没有这行,下面输出false,有输出:true
        public class SpringbootHelloworldQuickApplication {
            public static void main(String[] args) {
                SpringApplication.run(SpringbootHelloworldQuickApplication.class, args);
            }
        }
springboot不推荐编写spring 的配置文件:

<?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="cn.com.wmd.service.HelloService"></bean>
</beans>
推荐做法:
springboot推荐往容器中添加组件的方式:推荐使用全注解的方式
步骤:
    1.创建一个专门的配置类:Myconfig
    2.配置类代码如下:
        /**
         * @Configuration指明当前是个配置类:替代之前的spring配置文件
         * 在spring配置文件是<bean id="" class=""></bean>标签来添加组件
         */
        @Configuration--->指明当前是个配置类!
        public class Myconfig {
            //@Bean将方法的返回值添加到组件中,组件的id是方法的名称!!!是名称!!!
            @Bean
            public HelloService helloService(){
                System.out.println("HelloService组件添加到容器中!");
                return new HelloService();
            }
        }
        若此时的方法改为:public HelloService hello(){}则容器中会注入一个id是:hello,类型是:HelloService的组件

 

posted @ 2022-05-09 21:01  努力的达子  阅读(30)  评论(0编辑  收藏  举报