欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring-boot系列3:配置文件@ConfigurationProperties

程序员文章站 2024-01-09 20:16:52
...

熟悉spring的同学,都知道spring的xml配置文件。下面主要讲解一下@ConfigurationProperties注解类的用法。

知识点

@Configuation等价于<Beans></Beans>

@Bean等价于<Bean></Bean>

@ComponentScan等价于<context:component-scan base-package=”com.dxz.demo”/>

@ConfigurationProperties 主要用来把properties配置文件转化为bean(类)来使用的

需要引入的maven依赖:

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

举一个简单的案例,先了解一下,然后通过转载的一个博客来了解一下springboot的配置文件的详细讲解。

application.properties

userName=yunxi.shi
password=123456

UserPojo.java

package com.configuration;

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

@Configuration
@ConfigurationProperties
public class UserPojo {

	private String userName;
	private String password;
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "UserPojo [userName=" + userName + ", password=" + password + "]";
	}
	
}

DemoController.java

package com.controller;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.configuration.UserPojo;


 
@RestController
public class DemoController {
	
	@Autowired
	private  UserPojo user;

    @RequestMapping("/hello")
    public String hello(){
        return "hello,spring-boot!!!";
    }
    
    
    @RequestMapping("/user")
    public String user(){
        return user.toString();
    }
}

Application.java

package com.configuration;

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

@Configuration
@ConfigurationProperties
public class UserPojo {

	private String userName;
	private String password;
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "UserPojo [userName=" + userName + ", password=" + password + "]";
	}
	
}

spring-boot系列3:配置文件@ConfigurationProperties

配置文件的详解,我发现了一个很不多的博主写的。

【SpringBoot】— Spring Boot配置文件详解

相关标签: spring-boot