springboot的配置变量

获取配置信息

如果是被spring容器所管理,一般采用@Value注解就可以读取到application.yml文件的内容。

但是不被spring容器管理,使用@Value是无效的。注入时会是NULL。但就是会有这样的场景,此时可采用在springboot启动类中将环境注入到某一个公共配置类,该类所有属性为公共静态属性攻外部类直接使用。

java 复制代码
ConfigurableApplicationContext run = SpringApplication.run(DemoStarterTestApplication.class, args);
        ConfigurableEnvironment environment = run.getEnvironment();
        String address = environment.getProperty("server.address1");
        int age = Integer.parseInt(environment.getProperty("spring.user.age"));

原文链接:https://blog.csdn.net/weixin_42740540/article/details/124348851

继承PropertyResolver,里面可以操作配置参数

JDBC操作获取系统变量

    InputStream is =        ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
	Properties pros = new Properties();
	pros.load(is);
	String user = pros.getProperty("user");
	String password = pros.getProperty("password");
	String url = pros.getProperty("url");
	String driverClass = pros.getProperty("driverClass");


@SpringBootApplication
public class MybatisPlusDemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext run= SpringApplication.run(MybatisPlusDemoApplication.class, args);
        ConfigurableEnvironment environment = run.getEnvironment();
        String address = environment.getProperty("server.address1");
        String username = environment.getProperty("spring.datasource.username");
        int age = Integer.parseInt(environment.getProperty("spring.user.age"));
        String name = environment.getProperty("server.name");
        EnvConfig envConfig = new EnvConfig();
        envConfig.setAddress(address);
        envConfig.setAge(age);
        System.out.println("地址为"+EnvConfig.address+",年龄为"+EnvConfig.age+"名字是:"+name);

        //获取ioc容器中的组件名字并打印出来
        String[] userBeanNames = run.getBeanNamesForType(User.class);
        for (String s : userBeanNames){
            System.out.println("---user:"+s);
        }
        // 判断id为user01的对象是否存在
        boolean b = run.containsBean("user01");
        System.out.println(b);
        // 直接获取容器当中的user对象
        User bean = run.getBean(User.class);
        System.out.println(bean);


        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

        context.getEnvironment().setActiveProfiles("like");
        context.register(AppConfigWithActiveProfile.class, AppConfigWithInactiveProfile.class);
        context.refresh();
        Subject subject = (Subject) context.getBean("subject");
        System.out.println("subject = " + subject);

        // ------------------------------ 测试 DependsOn  ------------------------------
        AnnotationConfigApplicationContext contextDependsOn = new AnnotationConfigApplicationContext(AppConfigWithDependsOn.class);
        contextDependsOn.getBean(FirstBean.class);
        contextDependsOn.close();

    }

}

SecondBean Initialized via Constuctor

ThirdBean Initialized via Constuctor

FirstBean Initialized via Constuctor

Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.

Registered plugin: 'com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor@45792847'

Registered plugin: 'com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor@706cb08'

Parsed mapper file: 'file [D:\idea\gitDowload\WangPai1Zu\code\MybatisPlusDemo\target\classes\mapper\UserMapper.xml]'

_ _ |_ _ |. ___ _ | _

| | |\/|)(| | |\ |)|||\

/ |

3.5.1

地址为aa,年龄为19名字是:aa

---user:user01

true

User(id=null, name=null, createTime=null, updateTime=null, age=null, email=null)

subject = Subject{like='物理', wenke='null'}

SecondBean Initialized via Constuctor

ThirdBean Initialized via Constuctor

FirstBean Initialized via Constuctor

public class EnvConfig {
    public static String address;

    public static int age;

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

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

}

@Configuration
public class MyConfig {

    // 给容器中加入组件,以方法名作为组件id
    @Bean
    public User user01() {
        User user = new User();
        return user;
    }
}


@Profile("like")
@Configuration
public class AppConfigWithActiveProfile {

    @Bean
    public Subject subject(){
        Subject subject = new Subject();
        subject.setLike("物理");
        return subject;
    }

}

@Profile("wenke")
@Configuration
public class AppConfigWithInactiveProfile {

    @Bean
    public Subject subject(){
        Subject subject = new Subject();
        subject.setWenke("历史");
        return subject;
    }
}


@Data
// 学科
public class Subject {

    // 理科
    private String like;
    // 文科
    private String wenke;



    @Override
    public String toString() {
        return "Subject{" +
                "like='" + like + '\'' +
                ", wenke='" + wenke + '\'' +
                '}';
    }
}

public class FirstBean {

    @Autowired
    private SecondBean secondBean;

    @Autowired
    private ThirdBean thirdBean;

    public FirstBean() {
        System.out.println("FirstBean Initialized via Constuctor");
    }
}


@Configuration
public class AppConfigWithDependsOn {

    @Bean("firstBean")
    @DependsOn(value = {
            "secondBean",
            "thirdBean"
    })
    public FirstBean firstBean() {
        return new FirstBean();
    }

    @Bean("secondBean")
    public SecondBean secondBean() {
        return new SecondBean();
    }

    @Bean("thirdBean")
    public ThirdBean thirdBean() {
        return new ThirdBean();
    }
}

public class SecondBean {

    public SecondBean() {
        System.out.println("SecondBean Initialized via Constuctor");
    }
}
相关推荐
gentle_ice1 小时前
leetcode——矩阵置零(java)
java·算法·leetcode·矩阵
Future_yzx1 小时前
基于SpringBoot+WebSocket的前后端连接,并接入文心一言大模型API
spring boot·websocket·文心一言
whisperrr.2 小时前
【JavaWeb06】Tomcat基础入门:架构理解与基本配置指南
java·架构·tomcat
火烧屁屁啦3 小时前
【JavaEE进阶】应用分层
java·前端·java-ee
m0_748257463 小时前
鸿蒙NEXT(五):鸿蒙版React Native架构浅析
java
我没想到原来他们都是一堆坏人3 小时前
2023年版本IDEA复制项目并修改端口号和运行内存
java·ide·intellij-idea
bing_1584 小时前
Redis 的缓存穿透、缓存击穿和缓存雪崩是什么?如何解决?
redis·spring·缓存
Suwg2094 小时前
【由浅入深认识Maven】第1部分 maven简介与核心概念
java·maven
花心蝴蝶.5 小时前
Spring MVC 综合案例
java·后端·spring