@Component + @ConfigurationProperties 注解

配置绑定

如何使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用;

理解:这个过程就好比配置数据库时写了properties文件,然后我们通过java的流读取文件,然后连接数据库

@Component + @ConfigurationProperties

系统要求

Java 8+

Maven 3.6.6 +

创建Maven项目工程

引入 pom.xml 依赖
    <!--1.导入父工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
    </parent>

    <!--2.导入springBoot的Web场景-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
 <build>
        <!--
        SpringBoot项目默认打成jar包
            传统web项目我们需要打成war包,放入tomcat中运行,springBoot项目我们可以导入一个插件,
            在项目打成jar包的同时,还会顺带打包运行环境,所以只要直接运行jar包也可以访问项目
        -->
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
创建实体类 pojo.Cat类
package com.xiang.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * Created by IntelliJ IDEA.
 * User: xiang
 * Date: 2021/10/12 14:05
 */
/**
 * 只有在容器中的组件,才会拥有SpringBoot提供的功能,也就是才可以使用注解
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@ConfigurationProperties(prefix = "cat")
//该注解表示:从application.properties中读取前缀为cat的数据赋值给下列属性,注意文件中的属性名和实体类中的属性名一致
public class Cat {
    private  String name;
    private  double price;
}

application.properties文件
#在配置文件中给Cat这个实例赋值
cat.name="tom"
cat.price=500.00

主程序进行测试 MainApplication 类
package com.xiang;

import com.xiang.pojo.Cat;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * Created by IntelliJ IDEA.
 * User: xiang
 * Date: 2021/10/12 14:35
 */
@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(MainApplication.class, args);

        Cat cat = context.getBean("cat", Cat.class);
        System.out.println(cat);
        /**
         * Cat(name="tom", price=500.0)
         */
    }
}

运行结果
Cat(name="tom", price=500.0)

posted @ 2021-10-12 15:55  阿向向  阅读(461)  评论(0编辑  收藏  举报