spring-boot-configuration-processor加载配置文件注入controller

个人经常使用@Value注解的方式,其实springboot提供另外一种更加优雅的方式,就是我们现在要讲的
在pom.xml文件中增加如下依赖。

	   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>

在我们的对象上加入以下注解,我们就可以在controller层注入我们的对象

package com.hbk.springbootmail.model;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@ConfigurationProperties(prefix = "com.hbk")
@PropertySource(value = "classpath:hbk.properties")
public class Hbk {
    private String author;
    private int age;
    private String address;

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Hbk{" +
                "author='" + author + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }
}

hbk.properties文件放到工程resources目录下,因为编译会在classpath,内容如下:

com.hbk.author=huangbaokang
com.hbk.age=30
com.hbk.address=ganzhou
package com.hbk.springbootmail.controller;

import com.hbk.springbootmail.model.Hbk;
import com.hbk.springbootmail.model.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private Hbk hbk;

    @GetMapping("/hello")
    public User hello(){
        User user = new User();
        user.setId(1);
        user.setBirthday(new Date());
        user.setName("huangbaokang222");
        user.setPassword("123456");
        user.setDesc("描述2");
        return user;
    }

    @GetMapping("/test")
    public Hbk test(){
        Hbk result = new Hbk();
        BeanUtils.copyProperties(hbk, result);
        return result;
        // 直接return hbk会报序列化的问题,在这里new了一个对象,通过拷贝的方式解决了此问题。
    }
}

浏览器访问localhost:8008/user/test
在这里插入图片描述

发布了1184 篇原创文章 · 获赞 272 · 访问量 203万+

猜你喜欢

转载自blog.csdn.net/huangbaokang/article/details/104054281