Spring加载配置文件的三种方式

合集下载

在单元测试中加载配置文件的方法

在单元测试中加载配置文件的方法

在单元测试中加载配置文件的方法在单元测试中加载配置文件有以下几种方法:1. 使用测试配置文件:创建一个独立的测试配置文件,其中包含测试所需的配置信息。

在测试代码中加载该配置文件,以便在测试过程中使用。

```javaProperties properties = new Properties();try (InputStream inputStream =getClass().getClassLoader().getResourceAsStream("test-config.properties")) {properties.load(inputStream);} catch (IOException e) {// 处理异常}// 使用 properties 获取配置信息```2. 使用测试注解:在测试类或测试方法上使用特定的注解,如`@TestPropertySource`(Spring Boot)或`@RunWithConfigSettings`(JUnit 5),并指定加载的配置文件。

测试框架可以根据注解的配置自动加载和使用相应的配置文件。

```java@TestPropertySource("classpath:test-config.properties")public class MyTestClass {// 测试代码}```3. 使用 Mock 对象:对于依赖于配置文件的类或组件,在测试时,可以使用 Mock 对象模拟加载配置文件并返回预定义的配置值。

```javaclass ConfigLoader {public Properties load(String configFile) {// 加载配置文件并返回配置信息的 Mock 对象}}class MyTestClass {private ConfigLoader configLoader;@Beforepublic void setup() {configLoader = mock(ConfigLoader.class);Properties properties = new Properties();properties.setProperty("key1", "value1");properties.setProperty("key2", "value2");when(configLoader.load(anyString())).thenReturn(properties); }@Testpublic void testMethod() {// 使用 Mock 的配置信息进行测试String value1 =configLoader.load("config.properties").getProperty("key1");String value2 =configLoader.load("config.properties").getProperty("key2");// 断言测试结果}}```以上方法可以根据具体的测试需求选择适合的方式来加载配置文件,在测试过程中使用相应的配置信息。

ioc流程

ioc流程

ioc流程IOC,即控制反转(Inversion of Control),是一种由Spring框架引入,并广泛应用于Java开发中的设计模式。

它通过将对象的创建、依赖注入和生命周期管理等控制权转移到容器中,实现了代码的松耦合和模块间的解耦。

下面将详细介绍IOC的流程。

1. 配置文件的加载: IOC的流程首先是加载配置文件,Spring框架使用XML、注解或Java配置等方式来定义配置文件,其中包含了需要被管理的Bean的定义、相互依赖关系的配置以及其他配置项。

2. 容器的初始化: 加载完成配置文件后,Spring容器会初始化,创建一个IOC容器对象,并读取配置文件中的Bean定义信息,并将其转换为容器内的Bean对象。

3. Bean的实例化: IOC容器根据配置文件中的Bean定义信息,通过Java的反射机制或其他方式,实例化被管理的Bean对象。

根据配置的方式的不同,可以有三种实例化方式:构造器实例化、静态工厂方法实例化、实例工厂方法实例化。

4. 依赖注入: 依赖注入是IOC的核心概念,也是实现解耦的关键。

在依赖注入过程中,容器会根据配置文件中的依赖关系,将实例化好的Bean注入到其他Bean中。

依赖注入有三种方式:构造函数注入、Setter方法注入和接口注入。

5. Bean的生命周期管理: IOC容器会在Bean的实例化过程中,对其生命周期的管理。

生命周期包括Bean的初始化、使用和销毁三个阶段。

在Bean实例化后,容器会调用Bean的初始化方法,进行一些预处理操作。

在Bean的使用过程中,容器会监听Bean的特定事件,并执行相应的操作。

在容器关闭时,会调用Bean的销毁方法,进行一些资源的释放等操作。

6. 容器的关闭: 当容器使用完毕后,需要将其关闭。

在容器关闭时,会释放资源、销毁Bean实例等操作。

通常,我们会调用Spring提供的关闭方法,显式地关闭容器。

总结起来,IOC的流程包含了配置文件的加载、容器的初始化、Bean的实例化、依赖注入、Bean的生命周期管理和容器的关闭等过程。

SpringBoot框架中的配置文件加载

SpringBoot框架中的配置文件加载

SpringBoot框架中的配置文件加载在SpringBoot框架中,配置文件是非常重要的一部分,用于配置应用程序的各种参数和属性。

SpringBoot提供了多种方式来加载配置文件,以满足不同的需求和场景。

一、默认的配置文件加载在SpringBoot中,默认会加载名为"application.properties"或"application.yml"的配置文件。

这些文件可以放置在以下几个位置:1. 项目根目录下的"config"文件夹;2. 项目根目录下;3. classpath下的"config"文件夹;4. classpath下。

SpringBoot会按照上述顺序依次搜索并加载配置文件。

如果存在多个同名的配置文件,后加载的配置文件会覆盖前者的配置。

二、自定义的配置文件加载除了默认的配置文件加载方式,SpringBoot还支持自定义的配置文件加载。

我们可以通过使用@PropertySource注解来指定要加载的配置文件。

例如,我们可以创建一个名为"custom.properties"的配置文件,并在SpringBoot的主类中使用@PropertySource注解加载该文件:```java@Configuration@PropertySource("classpath:custom.properties")public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}```这样,SpringBoot会加载并解析"custom.properties"文件中的配置内容,并将其注入到应用程序中使用。

SpringBoot读取外部配置文件的方法

SpringBoot读取外部配置文件的方法

SpringBoot读取外部配置⽂件的⽅法1.SpringBoot配置⽂件SpringBoot使⽤⼀个以application命名的配置⽂件作为默认的全局配置⽂件。

⽀持properties后缀结尾的配置⽂件或者以yml/yaml后缀结尾的YAML的⽂件配置。

以设置应⽤端⼝为例properties⽂件⽰例(application.properties):server.port=80YAML⽂件⽰例(application.yml):server:port: 80在properties和yml/yaml配置⽂件同时存在的情况下, 在同⼀⽬录下,properties配置优先级 > YAML(YML)配置优先级2.配置⽂件⽬录SpringBoot配置⽂件可以放置在多种路径下,不同路径下的配置优先级有所不同。

可放置⽬录(优先级从⾼到低)./config/ (当前项⽬路径config⽬录下);./ (当前项⽬路径下);classpath:/config/ (类路径config⽬录下);classpath:/ (类路径config下).优先级由⾼到底,⾼优先级的配置会覆盖低优先级的配置;SpringBoot会从这四个位置全部加载配置⽂件并互补配置;我们可以从ConfigFileApplicationListener这类便可看出,其中DEFAULT_SEARCH_LOCATIONS属性设置了加载的⽬录:private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/";接着getSearchLocations⽅法中去逗号解析成Set,其中内部类Loader负责这⼀配置⽂件的加载过程,包括加载profile指定环境的配置,以application+’-’+name格式的拼接加载。

Spring注解@Value及属性加载配置文件方式

Spring注解@Value及属性加载配置文件方式

Spring注解@Value及属性加载配置⽂件⽅式Spring中使⽤@Value注解给bean加载属性的配置⽂件有两种使⽤⽅式第⼀种:使⽤@Value("#{configProperties['websit.msgname']}")spring中配置属性加载⽂件的配置⽅式<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"><property name="locations"><list><value>classpath:/properties/websit.properties</value></list></property></bean>注意1.这⾥使⽤的configProperties必须要和定义的bean名称⼀致。

2.websit⽤来指定msgname来源于那个配置⽂件3.配置的加载属性bean名称为org.springframework.beans.factory.config.PropertiesFactoryBean第⼆种:使⽤@Value("${websit.msgname}");使⽤这种⽅式,⼜可以有两种配置⽅式⽅式⼀<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"><property name="properties" ref="configProperties"/></bean><bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"><property name="locations"><list><value>classpath:/properties/websit.properties</value></list></property></bean>⽅式⼆<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations"><list><value>classpath:properties/websit.properties</value></list></property></bean>当使⽤@Value注解bean属性时,如果没有在配置⽂件中配置,这时启动spring就会抛出异常。

Spring中加载xml配置文件的几种方式

Spring中加载xml配置文件的几种方式

项目中一个需求就是所有的功能都是插件的形式装入系统,这就需要利用Spring去动态加载某一位置下的配置文件,就总结了下Spring中加载xml配置文件的方式, xml是最常见的spring 应用系统配置源。

Spring中的几种容器都支持使用xml装配bean,包括:XmlBeanFactory,ClassPathXmlApplicationContext,FileSystemXmlApplicationContext,XmlWebApplicationContext,.....一: XmlBeanFactory 引用资源1.Resource cr = new ClassPathResource("applicationContext.xml");BeanFactory bf=new XmlBeanFactory(cr);UserDao userDao = (UserDao)bf.getBean("userDao");二: ClassPathXmlApplicationContext 编译路径使用ClassPathXmlApplicationContext对象获取,必须把applicationContext.xml放置到类的加载路径中,也就是Src下面1.ApplicationContext factory=new ClassPathXmlApplicationContext("classpath:appcontext.xml");// src目录下的2.ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserDao userDao = (UserDao)context.getBean("userDao");3.ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext-oracle.xml","applicationContext.xml"});UserDao userDao = (UserDao)context.getBean("userDao");// src/conf 目录下的4.ApplicationContext factory=new ClassPathXmlApplicationContext("conf/appcontext.xml");5.ApplicationContext factory=new ClassPathXmlApplicationContext("file:G:/Test/src/appcontext.xml");三: FileSystemXmlApplicationContext用文件系统的路径必须把applicationContext.xml放置到工程目录下面,也就是项目路径的下面1.ApplicationContext factory=newFileSystemXmlApplicationContext("src/appcontext.xml");//使用了classpath: 前缀,作为标志, 这样,FileSystemXmlApplicationContext 也能够读入classpath下的相对路径没有classpath的话就是从当前的工作目录2.ApplicationContext factory=newFileSystemXmlApplicationContext("classpath:appcontext.xml");3.ApplicationContext factory=newFileSystemXmlApplicationContext("file:G:/Test/src/appcontext.xml");4.ApplicationContext factory=newFileSystemXmlApplicationContext("G:/Test/src/appcontext.xml");四: XmlWebApplicationContext是专为Web工程定制的。

java 引用外部配置文件的方法

java 引用外部配置文件的方法

java 引用外部配置文件的方法Java作为一种广泛应用的编程语言,经常需要引用外部配置文件来获取程序的设置参数。

本文将介绍几种常用的方法来实现这个目的。

一、使用Properties类Properties类是Java提供的一个用于处理配置文件的工具类,它可以读取和写入配置文件的键值对。

使用Properties类引用外部配置文件的步骤如下:1. 创建一个Properties对象。

2. 使用load()方法读取配置文件,将配置文件的内容加载到Properties对象中。

3. 使用getProperty()方法根据键名获取配置项的值。

下面是一个示例代码:```javaimport java.io.FileInputStream;import java.io.IOException;import java.util.Properties;public class ConfigReader {public static void main(String[] args) {Properties properties = new Properties();try {FileInputStream fis = newFileInputStream("config.properties");properties.load(fis);fis.close();} catch (IOException e) {e.printStackTrace();}String url = properties.getProperty("url");String username = properties.getProperty("username"); String password = properties.getProperty("password"); System.out.println("url: " + url);System.out.println("username: " + username);System.out.println("password: " + password);}}```在这个例子中,我们使用了一个名为config.properties的配置文件,其中包含了url、username和password三个配置项的值。

SpringBoot中的Properties的使用详解

SpringBoot中的Properties的使用详解

SpringBoot中的Properties的使用详解Properties文件的格式1. .properties文件:这是一种常用的配置文件格式,它使用"键=值"的形式来定义属性。

2. .yml文件:这是一种基于缩进的配置文件格式,它使用空格来表示层级关系,可以更加清晰地表示属性的结构。

Properties的加载顺序1. 配置文件的默认位置:Spring Boot会首先在默认的位置加载Properties文件,即在classpath下的/config文件夹或者是jar包的根目录下。

2. 配置文件的自定义位置:如果在默认位置找不到Properties文件,Spring Boot会尝试在工作目录下寻找,即在当前工作目录下的./config/文件夹或者是jar包的同级目录下。

3. 命令行参数:可以通过在启动应用程序时使用--和--spring.config.location参数来指定Properties文件的名称和位置。

Properties的使用在Spring Boot中,可以通过多种方式来使用Properties文件的属性值:Properties文件的加载和刷新在Spring Boot中,Properties文件的加载是在应用程序启动的过程中进行的,一旦加载完成,属性值将被缓存在内存中,并可以在整个应用程序中使用。

如果需要动态地从外部文件加载Properties文件的属性值,可以使用Spring的Environment对象,并通过调用其refresh(方法来刷新属性值。

总结Spring Boot中的Properties是一种用于配置应用程序的机制,可以通过多种方式来使用和获取属性值。

在Properties文件的加载和使用过程中,需要注意属性文件的加载顺序和使用方式,并可以根据自己的需求来选择合适的方式来使用Properties文件的属性值。

通过灵活地使用Properties,可以实现应用程序的动态配置和定制化。

springboot外部配置文件spring.config.location为什么不生效?

springboot外部配置文件spring.config.location为什么不生效?

springboot外部配置⽂件spring.config.location为什么不⽣效?⼀、背景原⽂链接 https:///trayvonnn/article/details/106239934 仅作分享,感谢作者本⽂写的是单应⽤下的springboot,并⾮微服务,如果是微服务可以参考nocos或者springcloud config。

⼀般在企业开发流⽔线中,都会涉及到⼏个环境的发布,dev开发环境,test测试环境,prod⽣产环境等等,那么如果需要发布⼀个项⽬到不同的环境会有⼏种⽅式:(个⼈拙见)第⼀,可以通过maven打包的⽅式指定特定环境的配置,这种⽅式就需要在打包的时候对环境做出区分,对于⼀些企业可能打包的⼯具是不区分环境的。

第⼆,也可以通过springboot运⾏时指定配置⽂件的环境,这样的话配置⽂件可能需要被管理在项⽬中,那么⽆法很好保护⽣产环境的配置。

第三,也可以通过环境变量的⽅式,区分不同环境的配置,这种⽅式缺点是要维护⼀份环境变量的⽂件,没有配置⽂件来的简便,不过也是⼀种⽅式。

最后就是就特定环境的配置放在服务器特定⽬录下,通过项⽬引⽤外部的配置⽂件来区分环境。

现在就按第四种展开。

先了解springboot的默认加载⽅式。

⼆、springboot 默认的配置⽂件加载顺序24.3 Application property filesSpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:A /config subdirectory of the current directory.The current directoryA classpath /config packageThe classpath rootThe list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations).这⾥说了四种⽅式可以把配置⽂件放到外部的。

ORA-12519-手工加载spring配置文件导致数据库session无法释放的问题

ORA-12519-手工加载spring配置文件导致数据库session无法释放的问题
迅速打开PLSQL,检查数据库session,Select Count(1) From v$session t Where t.SCHEMANAME='XXX';
随着service的执行,session数在增加,没有减少的意思。是的,当时就是这样。
解决思路:这种错误出现在久经考验的框架当中,我心里是相当不安的,居然会有这种低级趣味的错误。整理思路开始分析:这段代码唯一与以前不同的地方就是,我们在web应用中,是通过容器加载提供bean的,只有容器启动的时候才会加载xml。那么重点就应该是关注XML的加载方式了。
问题现象:在做web应用时会碰到这种情况,某些地方无法通过web当中的ApplicationContext来获得springIOC容器提供的bean,比如提供给外界的webservice接口,这个时候就需要手工通过ClassPathXmlApplicationContext等方式来获取ApplicationContext,代码如下:
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext-*.xml");
IXXXService xxxservice = (IXXX描述的很清楚。通过DisposableBean或者指定destroy-method都能很好的释放单例对象。而prototype类型的对象需要客户端显式的指定释放,释放对象完全是客户端控制,spring不负责释放。
所以,要改善context的加载方式,尽量的少多次去加载,实在没办法的情况下,一定要记得关闭。
这里实验一把,将ApplicationContext改成AbstractApplicationContext,执行context.close()。结果出来了,session已被正常回收,真相渐渐浮出水面。

Spring的常见问题及答案

Spring的常见问题及答案

Spring的常见问题及答案⽬录Spring 概述依赖注⼊Spring beansSpring注解Spring数据访问Spring⾯向切⾯编程(AOP)Spring MVCSpring 概述1. 什么是spring?Spring 是个java企业级应⽤的开源开发框架。

Spring主要⽤来开发Java应⽤,但是有些扩展是针对构建J2EE平台的web应⽤。

Spring 框架⽬标是简化Java企业级应⽤开发,并通过POJO为基础的编程模型促进良好的编程习惯。

2. 使⽤Spring框架的好处是什么?轻量:Spring 是轻量的,基本的版本⼤约2MB。

控制反转:Spring通过控制反转实现了松散耦合,对象们给出它们的依赖,⽽不是创建或查找依赖的对象们。

⾯向切⾯的编程(AOP):Spring⽀持⾯向切⾯的编程,并且把应⽤业务逻辑和系统服务分开。

容器:Spring 包含并管理应⽤中对象的⽣命周期和配置。

MVC框架:Spring的WEB框架是个精⼼设计的框架,是Web框架的⼀个很好的替代品。

事务管理:Spring 提供⼀个持续的事务管理接⼝,可以扩展到上⾄本地事务下⾄全局事务(JTA)。

异常处理:Spring 提供⽅便的API把具体技术相关的异常(⽐如由JDBC,Hibernate or JDO抛出的)转化为⼀致的unchecked 异常。

3. Spring由哪些模块组成 ?以下是Spring 框架的基本模块:Core moduleBean moduleContext moduleExpression Language moduleJDBC moduleORM moduleOXM moduleJava Messaging Service(JMS) moduleTransaction moduleWeb moduleWeb-Servlet moduleWeb-Struts moduleWeb-Portlet module4. 核⼼容器(应⽤上下⽂) 模块。

如何使用多个Spring的xml配置文件

如何使用多个Spring的xml配置文件

如何使用多个Spring的xml配置文件(多模块配置)在用Struts Spring Hibernate进行项目团队开发的时候,我们每个开发人员可能都会用到spring的配置文件,如果我们每个开放人员都用同一个的话,这样会给项目开发带来一定的影响,不过大家不用急,Spring为我们提供了很好的方法,我们可以写多个xml文件,然后将每个文件引入进来就行了,话不多说了,马上开始!!方法一、在web.xml中定义 contextConfigLocation参数.spring会使用这个参数加载.所有”逗号”分割的xml.如果没有这个参数,spring默认加载WEB-INF/applicationContext.xml文件(我们现在将Spring配置文件都放在WEB-INF下面)<context-param><param-name>contextConfigLocation</param-name><param-value>classpath*:conf/spring/applicationContext_core*.xml,classpath*:conf/spring/applicationContext_dict*.xml,classpath*:conf/spring/applicationContext_hibernate.xml,classpath*:conf/spring/applicationContext_staff*.xml,classpath*:conf/spring/applicationContext_security.xmlclasspath*:conf/spring/applicationContext_modules*.xmlclasspath*:conf/spring/applicationContext_cti*.xmlclasspath*:conf/spring/applicationContext_apm*.xml</param-value></context-param>contextConfigLocation 参数定义了要装入的 Spring 配置文件。

【springBoot】springboot获取资源文件的三种方式【两种情况下】

【springBoot】springboot获取资源文件的三种方式【两种情况下】

【springBoot】springboot获取资源⽂件的三种⽅式【两种情况下】⾸先声明⼀点,springboot获取资源⽂件,需要看是 1》从spring boot默认的application.properties资源⽂件中获取 2》还是从⾃定义的资源⽂件中获取带着这个想法去看下⾯⼏种⽅式===============================================================================================1》从spring boot默认的application.properties资源⽂件中获取先给出来application.properties的内容#⽅式1com.sxd.type1 = type1com.sxd.title1 = 使⽤@ConfigurationProperties获取配置⽂件#⽅式2com.sxd.type2 = type2com.sxd.title2 = 使⽤@Value获取配置⽂件#⽅式3com.sxd.type3 = type3com.sxd.title3 = 使⽤Environment获取资源⽂件#mapcom.sxd.login[username] = sxdcom.sxd.login[password] = admin123com.sxd.login[callback] = /sxdcgaq8080/#listList[0] = com1List[1] = com2List[2] = com3View Code①===第⼀种⽅式:使⽤@ConfigurationProperties获取配置⽂件先搞⼀个绑定资源⽂件的bean注意属性名和资源⽂件中的属性名相⼀致。

package com.sxd.beans;import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource;import ponent;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) {List = comList;}}View Code然后在启动类中使⽤package com.sxd.secondemo;import er;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 {@AutowiredUser 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了。

springMVC配置文件详解

springMVC配置文件详解

web.xml的配置web.xml应该是整个项目最重要的配置文件了,不过servlet3.0中已经支持注解配置方式了。

在servlet3.0以前每个servlet必须要在web.xml中配置servlet及其映射关系。

但是在spring框架中就不用了,因为Spring中是依赖注入(Dependency Injection)的也叫控制反转(Inversion of Control)。

但是也要配置一个重要的servlet,就是前端控制器(DispatcherServlet)。

配置方式与普通的servlet基本相似。

配置内容如下:<!-- 配置前端控制器--><servlet><servlet-name>spring</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><!-- ContextconfigLocation配置springmvc加载的配置文件适配器、处理映射器等--><param-name>contextConfigLocation</param-name><param-value>WEB-INF/classes/spring/springmvc.xml</param-value></init-param></servlet><servlet-mapping><servlet-name>spring</servlet-name><!-- 1、.action访问以.action结尾的由DispatcherServlet进行解析2、/,所有访问都由DispatcherServlet进行解析--><url-pattern>/</url-pattern></servlet-mapping>这里需要注意,springmvc.xml是spring配置文件,将在后面讨论。

SpringMVC的配置文件

SpringMVC的配置文件

SpringMVC的配置⽂件⼀、root标签跟spring配置⼀样,root标签是beans,毕竟springmvc是spring的⼀个模块在springmvc⾥,⾃动扫描主要是配置controller:⼆、⾃动扫描:⼆、⾃动扫描:在<context:component-scan base-package="com.xxx.controller"/>三、解析器Resolver:解析器有很多种,⽐较重要的是ViewResolverViewResolver也有很多种,其中⽐较重要和常⽤的是InternalResourceViewResolver(内部资源视图解析器)代码:<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/jsp/" /><property name="suffix" value=".jsp" /></bean>如果没有视图解析器,我们在controller⾥⾯的代码是这样的:@Controllerpublic class LoginActionController {@RequestMapping("/index")public String toIndex(HttpServletRequest request, ModelMap map, HttpSession session) {return "/WEB-INF/jsp/index.jsp";}⽽使⽤了视图解析器,我们的代码是这样的:@Controllerpublic class LoginActionController {@RequestMapping("/index")public String toIndex(HttpServletRequest request, ModelMap map, HttpSession session) {return "index";}区别在最后⼀句,我们不需要给出⽬标视图的全路径了。

第100天学习打卡(SpringBoot配置文件位置的加载顺序多环境切换dpringboo。。。

第100天学习打卡(SpringBoot配置文件位置的加载顺序多环境切换dpringboo。。。

第100天学习打卡(SpringBoot配置⽂件位置的加载顺序多环境切换dpringboo。

SpringBoot 配置⽂件位置的加载顺序1.file:./config2.file:./3.classpath:/config/4.classpath:/(默认)项⽬录的config优先级最⾼。

项⽬录的配置⽂件优先级第⼆。

resources下的config优先级第三。

resources下的配置⽂件优先级最低。

优先级由⾼到低,⾼优先级的配置会覆盖低优先级的配置;SpringBoot会从这四个位置全部加载主配置⽂件;互补配置;我们在最低的配置⽂件中设置⼀个项⽬访问路径的配置来测试互补问题;# 配置项⽬的访问路径server:servlet:context-path: /kuangserver.servlet.context-path=/kuang我们还可以通过spring.config.location来改变默认的配置⽂件位置项⽬打包好后,我们可以使⽤命令⾏参数的形式,启动项⽬的时候来指定配置⽂件的新位置;这种情况,⼀般是后期运维做的多,相同配置,外部指定的配置⽂件优先级最⾼。

java -jar spring-boot-config.jar --spring.config.location=F:/application.properties外部加载配置⽂件的⽅式⼗分多,我们选择最常⽤的即可,在开发的资源⽂件中进⾏配置。

多环境切换profile是spring对不同环境提供不同配置功能的⽀持,可以通过激活不同的环境版本,实现快速切换环境。

⽅式⼀:多配置⽂件我们在主配置⽂件编写的时候,⽂件名可以是application-{profile}.properties/yml,⽤来指定多个环境版本。

例如:application-test.properties代表测试环境配置 application-dev.properties代表开发环境配置但是SpringBoot并不会直接启动这些配置⽂件,它默认使⽤application.properties主配置⽂件;我们需要通过⼀个配置来选择需要激活的环境;# ⽐如在配置⽂件中指定使⽤dev环境,我们可以通过设置不同的端⼝号进⾏测试# 我们启动springboot,就可以看到已经切换到dev下的配置了spring.profiles.active=dev# springboot的多环境配置:可以选择激活哪⼀个配置⽂件spring.profiles.active=test⽅式⼆:yml的多⽂档块和properties配置⽂件,但是使⽤yml去实现不需要创建多个配置⽂件,更加⽅便。

springboot加载application配置文件源码分析

springboot加载application配置文件源码分析

springboot加载application配置⽂件源码分析springboot加载application.yml和application.properties原理监听器:ConfigFileApplicationListener、BootstrapApplicationListener1、系统启动时,调⽤SpringApplication.run()2、初始化监听器//初始化SpringApplicationRunListeners,并且初始化变量listeners,将EventPublishingRunListener存放与listeners中1)SpringApplicationRunListeners listeners = this.getRunListeners(args);2)3)SpringFactoriesLoader.loadSpringFactories()加载META-INF/spring.factories下的配置监听器3、调⽤ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);内部调⽤步骤如下1)listeners.environmentPrepared((ConfigurableEnvironment)environment);监听器的准备⼯作2)listener.environmentPrepared(environment);循环listeners中的监听器,执⾏environmentPrepared⽅法,其中加载配置⽂件的监听器就在循环列表中3)执⾏EventPublishingRunListener中的environmentPrepared()⽅法public void environmentPrepared(ConfigurableEnvironment environment) {this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent(this.application, this.args, environment));}4)SimpleApplicationEventMulticaster类中的doInvokeListener()⽅法5)执⾏ConfigFiledApplicationListerner类中的onApplicationEvent(event)⽅法6)执⾏ConfigFileApplicationListener中的onApplicationEnviromentPrepareEvent()⽅法private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) {List<EnvironmentPostProcessor> postProcessors = this.loadPostProcessors();postProcessors.add(this);AnnotationAwareOrderComparator.sort(postProcessors);Iterator var3 = postProcessors.iterator();while(var3.hasNext()) {EnvironmentPostProcessor postProcessor = (EnvironmentPostProcessor)var3.next();postProcessor.postProcessEnvironment(event.getEnvironment(), event.getSpringApplication());}}注意:AnnotationAwareOrderComparator.sort(postProcessors); 对List<EnvironmentPostProcessor>集合进⾏排序,排序规则按照spring中的注解@Order注解和@Priority注解排序7)迭代postPrccessors集合,并且执⾏集合中的postProcessEnvironment⽅法,重点看ConfigFileApplicationListener类中的postProcessEnvironment⽅法其中会添加⼀个属性源进来ResourceLoader8)调⽤load⽅法加载属性protected void addPropertySources(ConfigurableEnvironment environment, ResourceLoader resourceLoader) {RandomValuePropertySource.addToEnvironment(environment);(new ConfigFileApplicationListener.Loader(environment, resourceLoader)).load();}9) load⽅法中调⽤apply⽅法void load() {FilteredPropertySource.apply(this.environment, DEFAULT_PROPERTIES, LOAD_FILTERED_PROPERTY,(defaultProperties) -> {this.profiles = new LinkedList<>();this.processedProfiles = new LinkedList<>();this.activatedProfiles = false;this.loaded = new LinkedHashMap<>();initializeProfiles();while (!this.profiles.isEmpty()) {Profile profile = this.profiles.poll();if (isDefaultProfile(profile)) {addProfileToEnvironment(profile.getName());}load(profile, this::getPositiveProfileFilter,addToLoaded(MutablePropertySources::addLast, false));this.processedProfiles.add(profile);}load(null, this::getNegativeProfileFilter, addToLoaded(MutablePropertySources::addFirst, true));addLoadedPropertySources();applyActiveProfiles(defaultProperties);});}10) apply⽅法默认获取defaultProperties属性,如果获取为空,则从上⼀步中执⾏函数式编程中的accept⽅法,下边移步到accept⽅法⼀探究竟,⾸先apply⽅法中会执⾏⼀个初始化⽅法initializeProfiles,⽅法中会向profiles中放⼊null,然后再放⼊⼀个"default",⽤来从外部遍历,遍历为null的时候,加载springboot的默认配置,遍历为“default"时,加载⽤户配置,从⽽充分体现了约定⼤于配置11)遍历profiles集合,遍历的第⼀次为null,执⾏load⽅法如下private void load(Profile profile, DocumentFilterFactory filterFactory, DocumentConsumer consumer) {getSearchLocations().forEach((location) -> {boolean isDirectory = location.endsWith("/");Set<String> names = isDirectory ? getSearchNames() : NO_SEARCH_NAMES;names.forEach((name) -> load(location, name, profile, filterFactory, consumer));});}⾸先执⾏getSearchLocations⽅法,获取默认的路径,默认的路径为如果启动参数中有"spring.config.location",则加载spring.config.location中指定的配置⽂件,否则⽤默认的DEFAULT_SEARCH_LOCATIONS,classpath:/,classpath:/config/,file:./,file:./config/*/,file:./config/12)取出Locations为classpath:/,classpath:/config/,file:./,file:./config/*/,file:./config/遍历set,按照先后顺序取配置⽂件13)获取配置⽂件名字,如果配置的话,则去配置的名字,否则⽤默认的"application"14)取到location和name之后,执⾏load(String location, String name, Profile profile, DocumentFilterFactory filterFactory, DocumentConsumer consumer)⽅法,加载配置,如下图15 最终通过以钩⼦程序的形式调⽤函数式编程完成属性的赋值调⽤Map中的computeIfAbsent,如果不存在profile的key,则添加新的数据,并将value值返回。

SpringBoot获取配置文件的简单实现方法

SpringBoot获取配置文件的简单实现方法

SpringBoot获取配置⽂件的简单实现⽅法前⾔在讲SpringBoot 获取配置⽂件之前我们需要对SpringBoot 的项⽬有⼀个整体的了解,如何创建SpringBoot 项⽬,项⽬结构等等知识点,我在这⾥就不⼀⼀讲述了,没有学过的⼩伙伴可以⾃⼰在⽹上找⼀些资料进⾏学习,很简单的。

下⾯让我们开始今天的内容讲解吧。

⼀、SpringBoot 全局配置⽂件的加载顺序在SpringBoot 当中,全局配置⽂件有两种不同的格式,⼀个是我们常见的properties, ⼀种是yml.这两种格式的⽂件其实也没什么太⼤的区别,使⽤的时候按照个⼈的习惯来就⾏,下⾯我们⽤的是yml⽂件。

⾸先,当我们创建SpringBoot 的项⽬时,默认在resources⽬录下创建⼀个application.properties⽂件,这时我们可以在这个⽂件当中对项⽬进⾏配置即可。

但是在SpringBoot 中application.properties可以存放在以下⼏个位置:file:./config/ 项⽬根⽬录下的config⽂件夹下file:./ 项⽬根⽬录下classpath:/config/ 类路径下的config⽂件夹下classpath:/ 类路径下⽂件的加载顺序:即根⽬录下的config⽬录下,然后是根⽬录下,然后是classpath路径下的config⽬录下,最后是classpath路径下。

优先级由⾼到低,⾼优先级的配置会覆盖低优先级的配置。

假如:根⽬录下的config⽬录下定义端⼝为8084,根⽬录下定义端⼝为8083 ,classpath路径下的config⽬录定义端⼝为8082,classpath路径下定义端⼝为8081,最后启动,启动的端⼝为8084 ,⾼优先级会覆盖低优先级。

注意:并不是⾼优先级的被加载了,低优先级的就不会再加载,实际上是SpringBoot会从这四个位置全部加载主配置⽂件,并且还能产⽣互相配置的效果。

SpringBoot配置Druid三种方式(包括纯配置文件配置)

SpringBoot配置Druid三种方式(包括纯配置文件配置)

SpringBoot配置Druid三种⽅式(包括纯配置⽂件配置)记录⼀下在项⽬中⽤纯 YML(application.yml 或者 application.properties)⽂件、Java 代码配置 Bean 和注解三种⽅式配置 Alibaba Druid ⽤于监控或者查看 SQL 状况:1. 纯配置⽂件 .yml 或者 .properties(1)pom.xml 添加相关依赖<!-- SPRINGBOOT WEB --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- SPRINGBOOT DRUID --><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.10</version></dependency><!-- SPRINGBOOT JDBC --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><!-- MYSQL --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>${mysql-connector-java.version}</scope></dependency><!-- LOG4J --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.16</version><scope>compile</scope></dependency>(2)配置application.yml 或者 application.properties ⽂件,本次配置⽂件为application.ymlspring:# 数据源配置datasource:type: com.alibaba.druid.pool.DruidDataSource # MYSQL 5 驱动:com.mysql.jdbc.Driver,MYSQL 6+ 驱动:com.mysql.cj.jdbc.Driverdriver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=GMT%2B8username: rootpassword: 123456# 连接池配置druid:# 初始化⼤⼩,最⼩,最⼤initial-size: 5min-idle: 5max-active: 20# 配置获取连接等待超时的时间max-wait: 60000# 配置间隔多久才进⾏⼀次检测,检测需要关闭的空闲连接,单位毫秒time-between-eviction-runs-millis: 60000# 配置⼀个连接在池中最⼩⽣存时间min-evictable-idle-time-millis: 300000validation-query: SELECT 1 FROM sys_usertest-while-idle: truetest-on-borrow: falsetest-on-return: false# 打开 PSCache,并且指定每个连接上 PSCache 的⼤⼩pool-prepared-statements: truemax-pool-prepared-statement-per-connection-size: 20# 配置监控统计拦截的 Filter,去掉后监控界⾯ SQL ⽆法统计,wall ⽤于防⽕墙filters: stat,wall,log4j# 通过 connection-properties 属性打开 mergeSql 功能;慢 SQL 记录connection-properties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000# 配置 DruidStatFilterweb-stat-filter:enabled: trueurl-pattern: /*exclusions: .js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*# 配置 DruidStatViewServletstat-view-servlet:url-pattern: /druid/*# IP ⽩名单,没有配置或者为空,则允许所有访问allow: 127.0.0.1# IP ⿊名单,若⽩名单也存在,则优先使⽤deny: 192.168.31.253# 禁⽤ HTML 中 Reset All 按钮reset-enable: false# 登录⽤户名/密码login-username: rootlogin-password: 1232.Java 代码配置 Bean(1)pom.xml 依赖<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.10</version></dependency>(2)在配置⽂件 application.yml 中添加 Druid 配置spring:datasource:type: com.alibaba.druid.pool.DruidDataSource# 数据源的其他配置initialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true# 配置监控统计拦截的 filters,去掉后监控界⾯ sql ⽆法统计,'wall'⽤于防⽕墙filters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500(3)添加 DruidConfig.java 配置⽂件import javax.servlet.Filter;import javax.servlet.Servlet;import javax.sql.DataSource;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.alibaba.druid.pool.DruidDataSource;import com.alibaba.druid.support.http.StatViewServlet;import com.alibaba.druid.support.http.WebStatFilter;@Configurationpublic class DruidConfig {@Bean// 将所有前缀为spring.datasource下的配置项都加载DataSource中@ConfigurationProperties(prefix = "spring.datasource")public DataSource druidDataSource() {return new DruidDataSource();}@Beanpublic ServletRegistrationBean<Servlet> druidServlet() {// 进⾏ druid 监控的配置处理ServletRegistrationBean<Servlet> srb = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/**"); // ⽩名单srb.addInitParameter("allow", "127.0.0.1");// ⿊名单srb.addInitParameter("deny", "192.168.31.253");// ⽤户名srb.addInitParameter("loginUsername", "root");// 密码srb.addInitParameter("loginPassword", "root");// 是否可以重置数据源srb.addInitParameter("resetEnable", "false");return srb;}@Beanpublic FilterRegistrationBean<Filter> filterRegistrationBean() {FilterRegistrationBean<Filter> frb = new FilterRegistrationBean<>();frb.setFilter(new WebStatFilter());// 所有请求进⾏监控处理frb.addUrlPatterns("/*");// 排除名单frb.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.css,/druid/*");return frb;}}3.注解(1)pom.xml ⽂件中添加 Druid 依赖(同⽅式⼆)(2)配置⽂件添加信息(同⽅式⼆)(3)配置 WebServletimport javax.servlet.annotation.WebInitParam;import javax.servlet.annotation.WebServlet;import com.alibaba.druid.support.http.StatViewServlet;@WebServlet(urlPatterns = "/druid/*",initParams={@WebInitParam(name="allow",value="192.168.16.110,127.0.0.1"),// IP⽩名单 (没有配置或者为空,则允许所有访问)@WebInitParam(name="deny",value="192.168.16.111"),// IP⿊名单 (存在共同时,deny优先于allow)@WebInitParam(name="loginUsername",value="admin"),// ⽤户名@WebInitParam(name="loginPassword",value="admin"),// 密码@WebInitParam(name="resetEnable",value="false")// 禁⽤HTML页⾯上的“Reset All”功能})public class DruidServlet extends StatViewServlet {private static final long serialVersionUID = 1L;}(4)配置 WebFilterimport javax.servlet.annotation.WebFilter;import javax.servlet.annotation.WebInitParam;import com.alibaba.druid.support.http.WebStatFilter;@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",initParams={@WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略资源})public class DruidFilter extends WebStatFilter {}(5)配置启动⽂件SpringBootApplication ⽤于扫描我们配置的类添加 @ServletComponentScan 注解进⾏扫描import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.ServletComponentScan;@SpringBootApplication@ServletComponentScan("com.uy.servlet")public class SpringBootApplication{public static void main(String[] args) {SpringApplication.run(SpringBootApplication.class, args); } }到此这篇关于SpringBoot配置 Druid 三种⽅式(包括纯配置⽂件配置)的⽂章就介绍到这了,更多相关SpringBoot配置 Druid内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。

spring配置datasource三种方式数据库连接池

spring配置datasource三种方式数据库连接池

spring配置datasource三种⽅式数据库连接池尊重原创(原⽂链接):/kunkun378263/article/details/85063551、使⽤org.springframework.jdbc.datasource.DriverManagerDataSource说明:DriverManagerDataSource建⽴连接是只要有连接就新建⼀个connection,根本没有连接池的作⽤。

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName"><value>${jdbc.driverClassName}</value></property><property name="url"><value>${jdbc.url}</value></property><property name="username"><value>${ername}</value></property><property name="password"><value>${jdbc.password}</value></property></bean>2、使⽤mons.dbcp.BasicDataSource说明:这是⼀种推荐说明的数据源配置⽅式,它真正使⽤了连接池技术<bean id="dataSource" class="mons.dbcp.BasicDataSource"><property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value></property><property name="url"><value>jdbc:oracle:thin:@localhost:1521:orcl</value></property><property name="username"><value>test</value></property><property name="password"><value>test</value></property><property name="maxActive"><value>255</value></property><property name="maxIdle"><value>2</value></property><property name="maxWait"><value>120000</value></property></bean>3、使⽤org.springframework.jndi.JndiObjectFactoryBean说明:JndiObjectFactoryBean 能够通过JNDI获取DataSource<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"><property name="jndiName"><value>java:comp/env/jdbc/roseindiaDB_local</value></property></bean>总结:3种⽅式中的第⼀种没有使⽤连接池,故少在项⽬中⽤到,第三种⽅式需要在web server中配置数据源,不⽅便于部署,本⼈推荐使⽤每⼆种⽅式进⾏数据源的配置。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

1、把applicationContext.xml直接放在WEB-INF/classes下,spring会采用默认的加载方式
2、采用在web.xml中配置ContextLoaderListenera或ContextLoaderServlet指定加载路径方式。

它们两个有着同样的功能,都实现在了org.springframework.web.conte xt.ContextLoader类,都要定义contextConfigLocation参数。

区别在于listener不能在Servlet 2.2兼容的容器中使用。

自从Servelt 2.4规范,listener被要求在web应用启动后初始化。

web.xml初始化的时候,listerner会检查contextConfigLocation参数。

如果不存在的话,它将默认使用/WEB-INF/applicationContext.xml。

如果它存在,它就会用预先定义的分隔符(逗号,分号和空格)分开分割字符串(<param-value></para m-value),并将这些值作为应用上下文将要搜索的位置。

代码
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/daoContext.xml,
/WEB-INF/config/appContext1.xml,
/WEB-INF/config/appContext2.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener< /listener-class>
</listener>
<!-- 另一种是使用ContextLoaderServlet
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</s ervlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
-->
3 通过ClassPathXmlApplicationContext或XmlWebApplicationContext代码动态加

一:XmlBeanFactory 引用
Resource resource = new ClassPathResource("appcontext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
二:ClassPathXmlApplicationContext 编译路径
ApplicationContext factory=new
ClassPathXmlApplicationContext("classpath:appcontext.xml");
ApplicationContext factory=new
ClassPathXmlApplicationContext("appcontext.xml"); // src目录下的
ApplicationContext factory=new
ClassPathXmlApplicationContext("conf/appcontext.xml"); // src/conf 目录下的
ApplicationContext factory=new
ClassPathXmlApplicationContext("file:G:/Test/src/appcontext.xml");
三 : 用文件系统的路径
ApplicationContext factory=new
FileSystemXmlApplicationContext("src/appcontext.xml");
//使用了 classpath: 前缀,作为标志, 这
样,FileSystemXmlApplicationContext 也能够读入classpath下的相对路径
ApplicationContext factory=new
FileSystemXmlApplicationContext("classpath:appcontext.xml");
ApplicationContext factory=new
FileSystemXmlApplicationContext("file:G:/Test/src/appcontext.xml");
ApplicationContext factory=new FileSystemXmlApplicationContext("G:/Test/src/appcontext.xml");
四: XmlWebApplicationContext 是专为Web工程定制的。

ServletContext servletContext =
request.getSession().getServletContext();
ApplicationContext ctx =
WebApplicationContextUtils.getWebApplicationContext(servletContext );。

相关文档
最新文档