【spring Boot】spring boot获取资源文件的三种方式【两种情况下】

简介: 首先声明一点,springboot获取资源文件,需要看是  1》从spring boot默认的application.properties资源文件中获取  2》还是从自定义的资源文件中获取 带着这个想法去看下面几种方式====================================...

首先声明一点,springboot获取资源文件,需要看是

  1》从spring boot默认的application.properties资源文件中获取

  2》还是从自定义的资源文件中获取

 

带着这个想法去看下面几种方式

===============================================================================================

1》从spring boot默认的application.properties资源文件中获取

先给出来application.properties的内容

#方式1
com.sxd.type1 = type1
com.sxd.title1 = 使用@ConfigurationProperties获取配置文件

#方式2
com.sxd.type2 = type2
com.sxd.title2 = 使用@Value获取配置文件

#方式3
com.sxd.type3 = type3
com.sxd.title3 = 使用Environment获取资源文件

#map
com.sxd.login[username] = sxd
com.sxd.login[password] = admin123
com.sxd.login[callback] = http://www.cnblogs.com/sxdcgaq8080/

#list
com.sxd.comList[0] = com1
com.sxd.comList[1] = com2
com.sxd.comList[2] = com3
View Code

 

①===第一种方式:使用@ConfigurationProperties获取配置文件

先搞一个绑定资源文件的bean

注意属性名和资源文件中的属性名相一致。

package com.sxd.beans;


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@ConfigurationProperties(prefix = "com.sxd")
//@PropertySource("classpath:/application.properties")
//不用这个注解,默认就是加载application.properties资源文件
public class User {

    private String type1;
    private String title1;

    private Map<String,String> login = new HashMap<>();
    private List<String> comList = new ArrayList<>();

    public String getType1() {
        return type1;
    }

    public void setType1(String type1) {
        this.type1 = type1;
    }

    public String getTitle1() {
        return title1;
    }

    public void setTitle1(String title1) {
        this.title1 = title1;
    }

    public Map<String, String> getLogin() {
        return login;
    }

    public void setLogin(Map<String, String> login) {
        this.login = login;
    }

    public List<String> getComList() {
        return comList;
    }

    public void setComList(List<String> comList) {
        this.comList = comList;
    }
}
View Code

然后在启动类中使用

package com.sxd.secondemo;

import com.sxd.beans.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@SpringBootApplication
@EnableConfigurationProperties(User.class)
public class SecondemoApplication {


    @Autowired
    User user;


    @RequestMapping("/")
    public String hello(){
        user.getLogin().forEach((k,v)->{
            System.out.println("map的键:"+k+">>map的值:"+v);
        });

        user.getComList().forEach(i->{
            System.out.println("list的值:"+i);
        });

        return user.getType1()+user.getTitle1();
    }

    public static void main(String[] args) {
        SpringApplication.run(SecondemoApplication.class, args);
    }
}
View Code

 

结果如下:

控制台打印:

访问地址:

 

②===第二种方式:使用@Value获取配置文件

这里不用搞一个绑定资源文件的bean了。

只需要在你想用的地方使用@Value调用你想要的属性名对应的值即可。

package com.sxd.secondemo;

import com.sxd.beans.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@SpringBootApplication
public class SecondemoApplication {

    @Value("${com.sxd.type2}")
    private String type;

    @Value("${com.sxd.title2}")
    private String title;


    @RequestMapping("/")
    public String hello(){
        return type+title;
    }

    public static void main(String[] args) {
        SpringApplication.run(SecondemoApplication.class, args);
    }
}
View Code

 

访问结果:

 

③===第三种方式:使用Environment获取资源文件

也不用提前做什么使用,Environment就是一个全局的资源池,application.properties中的属性值都可以从这里获取到。

package com.sxd.secondemo;

import com.sxd.beans.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@SpringBootApplication
public class SecondemoApplication {

    @Autowired
    Environment environment;

    @RequestMapping("/")
    public String hello(){
        return environment.getProperty("com.sxd.type3")+environment.getProperty("com.sxd.title3");
    }

    public static void main(String[] args) {
        SpringApplication.run(SecondemoApplication.class, args);
    }
}
View Code

 

运行结果:

================================================================================================

2》从自定义的资源文件中获取属性值

①===第一种方式:使用@ConfigurationProperties获取配置文件

 自定义资源文件如下:

然后指定绑定自定义资源文件

package com.sxd.beans;


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;


@Component
@ConfigurationProperties(prefix = "com.sxd")
@PropertySource("classpath:/test.properties")
//需要用这个注解,默认就是加载application.properties资源文件,替换@ConfigurationProperties取消location属性的效果
public class User {

    private String type1;
    private String title1;


    public String getType1() {
        return type1;
    }

    public void setType1(String type1) {
        this.type1 = type1;
    }

    public String getTitle1() {
        return title1;
    }

    public void setTitle1(String title1) {
        this.title1 = title1;
    }


}
View Code

 

最后在启动类中使用一下

package com.sxd.secondemo;

import com.sxd.beans.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@SpringBootApplication
@EnableConfigurationProperties(User.class)
public class SecondemoApplication {

    @Autowired
    User user;

    @RequestMapping("/")
    public String hello(){
        return user.getType1()+user.getTitle1();
    }

    public static void main(String[] args) {
        SpringApplication.run(SecondemoApplication.class, args);
    }
}
View Code

 

 

运行结果:

 

②===第二种方式:使用@Value获取配置文件

先设定一个自定义资源文件

如下,自定义资源文件需要满足application-{profile}.properties格式

 

然后在application.properties文件中指明加载这个资源文件

spring.profiles.active=test
#spring.profiles.include=test

这两种哪种都可以加载上自定义的资源文件,后面的test就是上面{profile}的值

 

 最后在启动类中使用@Value获取自定义资源文件中的属性,这个时候自定义的资源文件已经在application,properties文件中被指明要被加载了,因此是可以被获取到的

package com.sxd.secondemo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@SpringBootApplication
public class SecondemoApplication {

    @Value("${com.sxd.type2}")
    private String type;
    @Value("${com.sxd.title2}")
    private String title;

    @RequestMapping("/")
    public String hello(){
        return type+title;
    }

    public static void main(String[] args) {
        SpringApplication.run(SecondemoApplication.class, args);
    }
}
View Code

 

运行结果:

③===第三种方式:使用Environment获取资源文件

 

 首先还是写一个自定义的资源文件,文件命名同上面第二种方式一样

接着,在application.properties中声明加载这个自定义的资源文件

最后在启动类中,也就是哪里使用就在那里自动注入Environment.

package com.sxd.secondemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@SpringBootApplication
public class SecondemoApplication {

    @Autowired
    Environment environment;

    @RequestMapping("/")
    public String hello(){
        return environment.getProperty("com.sxd.type3")+environment.getProperty("com.sxd.title3");
    }

    public static void main(String[] args) {
        SpringApplication.run(SecondemoApplication.class, args);
    }
}
View Code

 

 

运行结果:

 

==================================================================================================================

===================================================完成============================================================

 

相关文章
|
27天前
|
XML Java 应用服务中间件
Spring Boot 两种部署到服务器的方式
本文介绍了Spring Boot项目的两种部署方式:jar包和war包。Jar包方式使用内置Tomcat,只需配置JDK 1.8及以上环境,通过`nohup java -jar`命令后台运行,并开放服务器端口即可访问。War包则需将项目打包后放入外部Tomcat的webapps目录,修改启动类继承`SpringBootServletInitializer`并调整pom.xml中的打包类型为war,最后启动Tomcat访问应用。两者各有优劣,jar包更简单便捷,而war包适合传统部署场景。需要注意的是,war包部署时,内置Tomcat的端口配置不会生效。
202 17
Spring Boot 两种部署到服务器的方式
|
21天前
|
监控 Java 应用服务中间件
SpringBoot是如何简化Spring开发的,以及SpringBoot的特性以及源码分析
Spring Boot 通过简化配置、自动配置和嵌入式服务器等特性,大大简化了 Spring 应用的开发过程。它通过提供一系列 `starter` 依赖和开箱即用的默认配置,使开发者能够更专注于业务逻辑而非繁琐的配置。Spring Boot 的自动配置机制和强大的 Actuator 功能进一步提升了开发效率和应用的可维护性。通过对其源码的分析,可以更深入地理解其内部工作机制,从而更好地利用其特性进行开发。
42 6
|
1月前
|
缓存 安全 Java
Spring Boot 3 集成 Spring Security + JWT
本文详细介绍了如何使用Spring Boot 3和Spring Security集成JWT,实现前后端分离的安全认证概述了从入门到引入数据库,再到使用JWT的完整流程。列举了项目中用到的关键依赖,如MyBatis-Plus、Hutool等。简要提及了系统配置表、部门表、字典表等表结构。使用Hutool-jwt工具类进行JWT校验。配置忽略路径、禁用CSRF、添加JWT校验过滤器等。实现登录接口,返回token等信息。
346 12
|
1月前
|
存储 安全 Java
Spring Boot 3 集成Spring AOP实现系统日志记录
本文介绍了如何在Spring Boot 3中集成Spring AOP实现系统日志记录功能。通过定义`SysLog`注解和配置相应的AOP切面,可以在方法执行前后自动记录日志信息,包括操作的开始时间、结束时间、请求参数、返回结果、异常信息等,并将这些信息保存到数据库中。此外,还使用了`ThreadLocal`变量来存储每个线程独立的日志数据,确保线程安全。文中还展示了项目实战中的部分代码片段,以及基于Spring Boot 3 + Vue 3构建的快速开发框架的简介与内置功能列表。此框架结合了当前主流技术栈,提供了用户管理、权限控制、接口文档自动生成等多项实用特性。
81 8
|
2月前
|
缓存 前端开发 Java
【Spring】——SpringBoot项目创建
SpringBoot项目创建,SpringBootApplication启动类,target文件,web服务器,tomcat,访问服务器
|
3月前
|
监控 Java 数据库连接
详解Spring Batch:在Spring Boot中实现高效批处理
详解Spring Batch:在Spring Boot中实现高效批处理
461 12
|
3月前
|
安全 Java 测试技术
详解Spring Profiles:在Spring Boot中实现环境配置管理
详解Spring Profiles:在Spring Boot中实现环境配置管理
154 10
|
2月前
|
负载均衡 Java 开发者
深入探索Spring Cloud与Spring Boot:构建微服务架构的实践经验
深入探索Spring Cloud与Spring Boot:构建微服务架构的实践经验
207 5
|
3月前
|
存储 运维 安全
Spring运维之boot项目多环境(yaml 多文件 proerties)及分组管理与开发控制
通过以上措施,可以保证Spring Boot项目的配置管理在专业水准上,并且易于维护和管理,符合搜索引擎收录标准。
79 2
|
Java Spring
【spring boot】3.spring boot项目,绑定资源文件为bean并使用
整个例子的结构目录如下:   1.自定义一个资源文件 com.sxd.name = 申九日木 com.sxd.secret = ${random.value} com.sxd.intValue = ${random.
1037 0