spring boot @ConfigurationProperties和@EnableConfigurationProperties的作用和区别

学习SpringBoot时对这两个注解的作用理解的不是很清楚,特此记录一下:

@ConfigurationProperties:

被标注的类会使用外部文件给bean注入属性

示例:

menu类

application.yml:

menu:
  id: 1
  name: nema1
  url: url1
  parent_id: pid1
  menu_order: morder1
  menu_icon: micon1
  menu_type: mtype

test:

@RunWith(SpringRunner.class)
@SpringBootTest
public class CrudSpringbootEasyuiApplicationTests {

    @Autowired
    private Menu menu;

    @Test
    public void test() {
        System.out.println(menu);
    }
}

输出:

Menu{id=1, name='nema1', url='url1', parent_id='pid1', menu_order='morder1', menu_icon='micon1', menu_type='mtype1'}

这里我配合@Component一起使用,先将menu类注册为bean,再通过@ConfigurationProperties注解使用外部yml文件将属性注入。 其实也可以配合任何可以将一个类注册为bean的注解一起使用,Springboot内部经常配合@Bean一起使用。

 

@EnableConfigurationProperties:

作用:启用配置属性类

示例:

MyServerConfigurationProperties类:

@ConfigurationProperties(prefix = "myserver")
public class MyServerConfigurationProperties {
    private int port;
    private String url;
    private String brand;

    //省略get set方法    
}

application.yml

myserver:
  port: 8080
  url: localhost
  brand: alibaba

test:

@RunWith(SpringRunner.class)
@SpringBootTest
@EnableConfigurationProperties(MyServerConfigurationProperties.class)
public class CrudSpringbootEasyuiApplicationTests {

	@Autowired
	private MyServerConfigurationProperties properties;

	@Test
	public void test() {
		int port = properties.getPort();
		String url = properties.getUrl();
		String brand = properties.getBrand();

		System.out.println("port: " + port);
		System.out.println("url: " + url);
		System.out.println("brand: " + brand);
	}
}

配置了一个MyServerConfigurationProperties类,编写了yml文件,并在test类上添加了@EnableConfigurationProperties注解,将value设置为MyServerConfigurationProperties.class,这样在该类中就可以将该Properties类注入并使用了。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值