码迷,mamicode.com
首页 > 其他好文 > 详细

@Configuration+@ConfigurationProperties+@EnableCo

时间:2020-03-04 12:36:30      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:ref   gis   system   gap   dem   http   ring   contex   this   

@Configuration+@ConfigurationProperties+@EnableConfigurationProperties

技术图片

最佳设计方案(现在又改板了):

Bean上面直接设置@ConfigurationProperties

//需要依赖spring-boot-configuration-processor

@ConfigurationProperties(prefix = "stu")

public class Stu {

String name;

public Stu(String name) {

    this.name = name;

}

public Stu() {

}

public String getName() {

    return name;

}

public void setName(String name) {

    this.name = name;

}

@Override

public String toString() {

    return "Stu{" +

            "name=‘" + name + ‘\‘‘ +

            ‘}‘;

}

}

方式一:configuration上面跟随@EnableConfigurationProperties【这种情况只有configuration里面一个Bean 】

@Configuration

@EnableConfigurationProperties

public class StuConfiguration {

@Bean

public Stu stu(){

    return  new Stu();

}

}

方式二:configuration上面跟随@EnableConfigurationProperties【这种情况只有configuration里面一个Bean 】

package com.example.demo11.configuration;

import com.example.demo11.entity.Stu;

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

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

//@EnableConfigurationProperties(Stu.class),如果携带class参数则有用注册Bean的能力,

//因为实现了ImportBeanDefinitionRegistrar接口,Import三插之一

//这里的Bean名称非常有意思【类型名称+全包名】

@EnableConfigurationProperties(Stu.class)

public class StuConfiguration {

@Bean

public Stu stu2(){

    return  new Stu();

}

}

启动查看

@SpringBootApplication

public class Demo11Application {

public static void main(String[] args) {

    ConfigurableApplicationContext context = SpringApplication.run(Demo11Application.class, args);

    Stu stu = context.getBean("stu-com.example.demo11.entity.Stu", Stu.class);

    System.out.println(context.getBeansOfType(Stu.class).size());

    System.out.println(stu.toString());

    context.close();

}

}

@Configuration+@ConfigurationProperties+@EnableCo

标签:ref   gis   system   gap   dem   http   ring   contex   this   

原文地址:https://blog.51cto.com/14698881/2475340

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!