springboot 自动配置@ConfigurationProperties

本文介绍如何在Spring Boot中使用@ConfigurationProperties注解进行属性注入,包括将注解应用于@Bean方法和类级别,以及通过单元测试验证配置的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.加在@Bean

package com.knife.EhcacheBoot;

public class ServiceA {

	private String id;
	private String name;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String toString(){
		return "[id:"+id+",name:"+name+"]";
	}
}
package com.knife.EhcacheBoot;

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

@Configuration
public class Config {

	@Bean
	@ConfigurationProperties(prefix = "service")
	public ServiceA createServiceA() {
		return new ServiceA();
	}

}

配置文件

service.id=001
service.name=test

测试

package com.knife.EhcacheBoot;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = App.class)//这里的App是springboot的启动类名
@WebAppConfiguration
public class UnitTest {

	
	@Autowired
	ServiceA sa;
	
	@Test
	public void test(){
		System.out.println(sa);
	}
}

结果

[id:001,name:test]

2.加在class上

package com.knife.EhcacheBoot;

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

@ConfigurationProperties(prefix = "service")
public class ServiceA {

	private String id;
	private String name;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String toString(){
		return "[id:"+id+",name:"+name+"]";
	}
}
package com.knife.EhcacheBoot;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {

	@Bean
	public ServiceA createServiceA() {
		return new ServiceA();
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值