springbot---配置绑定

@ConfigurationProperties和component
功能:
  使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用;
实体类
package com.atguigu.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 只有在容器中的组件,才会拥有springboot提供的强大功能
 */
@Component//表明将这个类放在容器中

@ConfigurationProperties(prefix = "mycar")//配置文件的前缀 public class Car { private String brand; private Integer price; public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } @Override public String toString() { return "Car{" + "brand='" + brand + '\'' + ", price=" + price + '}'; } }

配置配置文件:application.properties

mycar.brand=byd
mycar.price=100000

测试,编写一个controller,返回该对象看页面是否返回一个有值的对象

package com.atguigu.controller;

import com.atguigu.bean.Car;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
    @Autowired
    Car car;
@RequestMapping(
"/car") public Car car(){ return car; } }

成功

 

 

@ConfigurationProperties和@EnableConfigurationProperties(Car.class)连用

实体类

package com.atguigu.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 只有在容器中的组件,才会拥有springboot提供的强大功能
 */
@ConfigurationProperties(prefix = "mycar")//配置文件的前缀
public class Car {
    private String brand;
    private Integer price;

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
}

config也就是spring配置类myconfig

@Configuration(proxyBeanMethods = true)//告诉spring这是一个配置类,相当于xml配置文件
@EnableConfigurationProperties(Car.class)
public class MyConFig {
    /**
     * 配置类无论调用多想遍方法,对象都是同一个对象,单例模式
     */
    @Bean//给容器添加组件,默认方法名就是组件id,返回值类型就是组件类型,返回的值就是组件的实例,也就是赋值
    public User user(){
        User user =  new User("小王",14);
        user.setPet(pet());
        return user;
    }
    @Bean("tom")//可以给bean取别名,否则就是方法名
    public Pet pet(){
        return new Pet("tomcat");
    }
}

controller

@RestController
public class HelloController {
    @Autowired
    Car car;

    @RequestMapping("/car")
    public Car car(){
        return car;
    }


    @RequestMapping("/hello")
    public String get(){
        return "hello boot"+"你好";
    }

}

...

 

 
posted @ 2021-12-12 09:54  江南0o0  阅读(38)  评论(0编辑  收藏  举报