对于想了解修改活动配置文件并刷新SpringBoot应用程序中的ApplicationContext运行时的读者,本文将提供新的信息,我们将详细介绍springboot配置文件动态刷新,并且为您提供关
对于想了解修改活动配置文件并刷新Spring Boot应用程序中的ApplicationContext运行时的读者,本文将提供新的信息,我们将详细介绍springboot配置文件动态刷新,并且为您提供关于applicationContext.xml import spring模块配置文件、junit 集成 spring 报错: GenericApplicationContext cannot be cast to WebApplicationContext、spring applicationContext.xml 配置文件 详解、Spring applicationContext配置文件约束文档整理的有价值信息。
本文目录一览:- 修改活动配置文件并刷新Spring Boot应用程序中的ApplicationContext运行时(springboot配置文件动态刷新)
- applicationContext.xml import spring模块配置文件
- junit 集成 spring 报错: GenericApplicationContext cannot be cast to WebApplicationContext
- spring applicationContext.xml 配置文件 详解
- Spring applicationContext配置文件约束文档整理
修改活动配置文件并刷新Spring Boot应用程序中的ApplicationContext运行时(springboot配置文件动态刷新)
我有一个Spring Boot Web应用程序。使用 @Configurable
批注通过Java类配置应用程序。我介绍了两个配置文件:“安装”,“正常”。如果安装概要文件处于活动状态,则不会加载任何需要DB连接的Bean。我想创建一个控制器,用户可以在其中设置数据库连接参数,完成后,我想将活动配置文件从“安装”切换为“普通”并刷新应用程序上下文,以便Spring可以初始化每个需要的bean
DB数据源。
我可以通过代码修改活动配置文件列表,没有问题,但是当我尝试刷新应用程序上下文时,出现以下 异常 :
`java.lang.IllegalStateException: GenericApplicationContext does not support multiple refresh attempts: just call ''refresh'' once`
这就是我启动Spring Boot应用程序的方式:
`new SpringApplicationBuilder().sources(MyApp.class).profiles("my-profile").build().run(args);`
有人知道如何启动Spring Boot应用程序,让您多次刷新应用程序上下文吗?
答案1
小编典典- 您不能只是刷新现有上下文。您必须关闭旧的并创建一个新的。您可以在这里查看我们如何在Spring
- Cloud中做到这一点:[https](https://github.com/spring-cloud/spring-cloud-
- commons/blob/master/spring-cloud-
- context/src/main/java/org/springframework/cloud/context/restart/RestartEndpoint.java)
- //github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-
context/src/main/java/org/springframework/ cloud / context / restart /
RestartEndpoint.java。如果您愿意,可以Endpoint
仅通过添加spring-
cloud-context作为依赖项来包含它,或者可以复制我猜想的代码并在自己的“端点”中使用它。
这是端点实现(字段中缺少一些详细信息):
@ManagedOperationpublic synchronized ConfigurableApplicationContext restart() { if (this.context != null) { if (this.integrationShutdown != null) { this.integrationShutdown.stop(this.timeout); } this.application.setEnvironment(this.context.getEnvironment()); this.context.close(); overrideClassLoaderForRestart(); this.context = this.application.run(this.args); } return this.context;}
applicationContext.xml import spring模块配置文件
applicationContext.xml import spring模块配置文件
在struts2 + spring + hibernate集成开发柜架中,spring的配置文件也可以分模块,然后在applicationContext.xml中引入即可,方法如下:
<?xml version="1.0" encoding="UTF-8"?>
- <beans
- xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
- <!--引用各模块的spring配置文件-->
- <importresource="conf/partner/partner-spring.xml"></import>
- </beans>
但需要注意的是resource中引入的文件的地址要用相对路径,不然会出错。
junit 集成 spring 报错: GenericApplicationContext cannot be cast to WebApplicationContext
公司这个项目,不是我来配置构建的, 把 spring 的配置什么的,和 springmvc 的配置没有区分开来,都是在一个配置文件里面,也就是 springmvc 里面。 和我们一般的 配置不一样,我们一般配置都是 配置好 spring 容器的,,然后配置好 springmvc 的分开来。 可是 这个项目不是这样的,,,感觉是有点乱,后期也难维护管理。。。
没办法了。 这个项目,他们是没有 junit 的, 估计他们不喜欢用吧。 可是我是有点喜欢 junit 测试的。 所以想自己集成 junit ,在写代码的时候,方便自己测试使用。
可是在集成的时候 junit 的时候 居然报错了。。。
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:539)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:761)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:461)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:207)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ''initService'' defined in file [D:\SVN\rpd-p2p\branches\1.3.1.shortcutpay\rpd-p2p\build\classes\com\moneyP2P\p2p\VSFP\spring\service\InitService.class]: Initialization of bean failed; nested exception is java.lang.ClassCastException: org.springframework.context.support.GenericApplicationContext cannot be cast to org.springframework.web.context.WebApplicationContext
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:120)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
... 25 more
Caused by: java.lang.ClassCastException: org.springframework.context.support.GenericApplicationContext cannot be cast to org.springframework.web.context.WebApplicationContext
at com.moneyP2P.p2p.VSFP.spring.service.InitService.setApplicationContext(InitService.java:251)
at org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:117)
at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:92)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:396)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1505)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
... 39 more
什么意思啊。。。? 百度一下,,,发现这样的问题实在是太少了。。。 使用网上的办法发现也不行啊。 我一点点看的时候,发现是在 某个 service 类初始化的时候,报错了。 这个 service implements ApplicationContextAware 这类。 按理来说,应该可以获取到啊,和 junit 测试看起来是没有问题的。。 继续看报错信息,说是某一些报错了
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
ServletContext application = ((WebApplicationContext) applicationContext)
.getServletContext();
application.setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
applicationContext);
columnServic.queryAllTopics(application);
application.setAttribute("application_link", linkService.query());
application.setAttribute("application_banner", bannerService.query());
//页面底部信息
application.setAttribute("footer", footerservice.queryFooter());
//页面系统信息
application.setAttribute("sysconfig", syscfgService.getSysConfig());
initEnumStatus(application);
initSetSafetyQuestion(application);
initSetServiceUser(application);
}
看到了? 这里 是 WebApplicationContext , 和 web 相关要拿到 servlet 容器相关的。 我们一般都是 直接获取 ApplicationContext 就可以了。 而我的 junit 测试,只是想 测试 spring 的 service 而已,并不是 controller 类。 但是这里是 要获取 WebApplicationContext 类的,所以执行 junit 初始化的时候获取不到就报错了。 并且也试过在 junit 测试的之前,构建 WebApplicationContext ,结果也是不行的。
因此只能 使用 junit 的 web 测试 方式来了,这样应该就可以了。 构建来了之后果然可以了。 下面是我的 junit spring mvc 测试类
package com.mytest.junit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.moneyP2P.p2p.VSFP.spring.controller.test.MyTestController;
import com.moneyP2P.p2p.VSFP.spring.service.UserBaseInfoService;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = "classpath*:config/main/spring-mvc.xml")
// 默认不回滚, 如果需要 回滚,请自己 在方法 加上 回滚, @Rollback(true) 或者是 defaultRollback = true
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
// extends AbstractTransactionalJUnit4SpringContextTests
public class MyJunitTest extends AbstractTransactionalJUnit4SpringContextTests {
// @Autowired
// private WebApplicationContext wac;
@Autowired
private MyTestController myTestController;
private MockMvc mockMvc;
@Autowired
private UserBaseInfoService userBaseInfoService;
@Before
public void setup() {
// 模拟web必须有这个 构建代码否则报错
mockMvc = MockMvcBuilders.standaloneSetup(myTestController).build();
}
@Test
public void test() {
System.out.println("==");
System.out.println(userBaseInfoService.queryUserById(113L).getUserName());
}
}
这样我们写 test 方法的时候,直接就获取 spring 的 bean 来测试了,或者说想 mockMVC 使用 controller 来测试 也是可以的。
参考 http://andy-ghg.iteye.com/blog/1772215
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:applicationContext-core.xml",
"classpath:applicationContext-servlet.xml" })
public class TestController {
@Autowired
private WebApplicationContext wac;
@Autowired
private SYSUserController userController;//你要测试的Controller
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
}
@Test
public void testFindPageUsers() throws Exception {
ResultActions ra = this.mockMvc.perform(MockMvcRequestBuilders
.post("/sysconfig/user/findPageUsers")
.accept(MediaType.APPLICATION_JSON).param("page", "1")
.param("limit", "10"));
MvcResult mr = ra.andReturn();
String result = mr.getResponse().getContentAsString();
log.info(result);
}
}
spring applicationContext.xml 配置文件 详解
applicationContext.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 自动扫描web包 ,将带有注解的类 纳入spring容器管理 -->
<context:component-scan base-package="com.eduoinfo.finances.bank.web"></context:component-scan>
<!-- 引入jdbc配置文件 -->
<bean id="propertyConfigurer">
<property name="locations">
<list>
<value>classpath*:jdbc.properties</value>
</list>
</property>
</bean>
<!-- dataSource 配置 -->
<bean id="dataSource"init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="20" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT ''x''" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="false" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat" />
</bean>
<!-- mybatis文件配置,扫描所有mapper文件 -->
<bean id="sqlSessionFactory"p:dataSource-ref="dataSource" p:configLocation="classpath:mybatis-config.xml" p:mapperLocations="classpath:com/eduoinfo/finances/bank/web/dao/*.xml" />
<!-- spring与mybatis整合配置,扫描所有dao -->
<beanp:basePackage="com.eduoinfo.finances.bank.web.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory" />
<!-- 对dataSource 数据源进行事务管理 -->
<bean id="transactionManager"p:dataSource-ref="dataSource" />
<!-- 配置使Spring采用CGLIB代理 -->
<aop:aspectj-autoproxy proxy-target-/>
<!-- 启用对事务注解的支持 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Cache配置 -->
<cache:annotation-driven cache-manager="cacheManager" />
<bean id="ehCacheManagerFactory"p:configLocation="classpath:ehcache.xml" />
<bean id="cacheManager"p:cacheManager-ref="ehCacheManagerFactory" />
</beans>
1、<context:component-scan base-package="com.eduoinfo.finances.bank.web"></context:component-scan> 作用
Spring 容器初始化的时候,会扫描 com.eduoinfo.finances.bank.web下 标有 (@Component,@Service,@Controller,@Repository) 注解的 类 纳入spring容器管理
在类上 ,使用以下注解,实现bean 的声明
@Component 泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
@Service 用于标注业务层组件
@Controller 用于标注控制层组件(如srping mvc的controller,struts中的action)
@Repository 用于标注数据访问组件,即DAO组件
示例:
@Controller
@RequestMapping(value = "/test")
public class TestController {
}
------------------------------------------------------------------------------------------------------------------
在类的成员变量上,使用以下注解,实现属性的自动装配
@Autowired : 按类 的 类型进行装配
@Resource (推荐) : 1 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
3.如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
4.如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;
@Resource注解在字段上,这样就不用写setter方法了,并且这个注解是属于J2EE的,减少了与spring的耦合。
示例:
@Resource
private TestServiceImpl testServiceImpl;
Spring applicationContext配置文件约束文档整理
applicationContext.xml配置文件内容:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
</beans>
今天关于修改活动配置文件并刷新Spring Boot应用程序中的ApplicationContext运行时和springboot配置文件动态刷新的介绍到此结束,谢谢您的阅读,有关applicationContext.xml import spring模块配置文件、junit 集成 spring 报错: GenericApplicationContext cannot be cast to WebApplicationContext、spring applicationContext.xml 配置文件 详解、Spring applicationContext配置文件约束文档整理等更多相关知识的信息可以在本站进行查询。
本文标签: