首页 文章资讯内容详情

SpringBoot获得application.properties中数据的几种方式

2026-06-01 4 花语

本文内容纲要:

-转:https://blog.csdn.net/qq_27298687/article/details/79033102 -SpringBoot获得application.properties中数据的几种方式 - -第一种方式 -第二种方式(自动装配到Bean中) -第三种方式(使用@value注解)

转:https://blog.csdn.net/qq_27298687/article/details/79033102

SpringBoot获得application.properties中数据的几种方式

第一种方式

[html]viewplaincopy

@SpringBootApplication publicclassSpringBoot01Application{ publicstaticvoidmain(String[]args){ ConfigurableApplicationContextcontext=SpringApplication.run(SpringBoot01Application.class,args); <spanstyle="color:#FF0000;">Stringstr1=context.getEnvironment().getProperty("aaa"); System.out.println(str1); } }

第二种方式(自动装配到Bean中)

[html]viewplaincopy

importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.core.env.Environment; importorg.springframework.stereotype.Component; @Component publicclassStudent{ @Autowired privateEnvironmentenv; publicvoidspeak(){ System.out.println("=========>"+env.getProperty("aaa")); } }

第三种方式(使用@value注解)

[html]viewplaincopy

packagecom.example.demo.entity;

importorg.springframework.beans.factory.annotation.Value;

importorg.springframework.context.annotation.PropertySource;

importorg.springframework.stereotype.Component;

@Component

@PropertySource("classpath:jdbc.properties")//如果是application.properties,就不用写@PropertySource("application.properties"),其他名字用些

publicclassJdbc{

@Value("${jdbc.user}")

privateStringuser;

@Value("${jdbc.password}")

privateStringpassword;

publicvoidspeack(){

System.out.println("username:"+user+"------"+"password:"+password);

}

}

本文内容总结:转:https://blog.csdn.net/qq_27298687/article/details/79033102,SpringBoot获得application.properties中数据的几种方式,,第一种方式,第二种方式(自动装配到Bean中),第三种方式(使用@value注解),

原文链接:https://www.cnblogs.com/aknife/p/11905920.html