I'm using spring-boot to start an HTTP server. It contains the following two files:
BeanUtils
#Service
public class BeanUtils implements ApplicationContextAware {
public static ApplicationContext cxt;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
cxt = applicationContext;
}
}
MainController
#RestController
public class MainController {
#GetMapping("/getData")
public Object getData() {
return BeanUtils.cxt.getBean("someBean").getData();
}
}
Does spring guarantee to finish all the beans, including both BeanUtils and MainController when the server starts? If not, the user might get a NullPointerException when he/she tried to access /getData because the BeanUtils bean hasn't been loaded. I want to know if it's safe to write like this.
you can try it. before send /getData request, BeanUtils has been loaded when server starts.
all the beans are instantiated on starting up in Spring IOC container, if it is a singleton bean(as are by default) an instance of bean is created at startup and passed wherever required and if not(prototype), an instance is created at the time required and passed. so in this case you won't get NullPointerException.
I have a data access class which runs as part of a stand-alone java application. It is currently working which means that a transaction manager is defined but I want to refactor the class to reduce the scope of the transaction but if I do I get org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here which implies that moving the #Transactional has somehow stopped it from being recognised.
My original version had the refactored methods being private but I found a recommendation to change that to public as in some cases the annotation would not be picked up.
public class DoStuff {
#Transactional
public void originalMethod() {
// do database stuff
...
// do non-database stuff that is time consuming
...
}
}
What I want to do is refactor to the following
public class DoStuff {
public void originalMethod() {
doDatabaseStuff()
doNonDatabaseStuff()
}
#Transactional
public void doDatabaseStuff() {
...
}
public void doNonDatabaseStuff() {
...
}
}
Edit:
You need to understand how Spring proxying works to understand why your refactoring does not work.
Method calls on the object reference will be calls on the proxy, and as such the proxy will be able to delegate to all of the interceptors (advice) that are relevant to that particular method call. However, once the call has finally reached the target object, any method calls that it may make on itself, are going to be invoked against the this reference, and not the proxy. This has important implications. It means that self-invocation is not going to result in the advice associated with a method invocation getting a chance to execute.
#Transactional uses Spring AOP, Spring uses proxies. This means that when you call an #Transactional method from another class, Spring will use a proxy, so the transactional advice will be applied. However, if you call the method from the same class, spring will use the "this" reference instead of the proxy, so that transactional advice will not be applied.
Original Answer:
Here is what worked for me in similar scenario.
public class DoStuff implement ApplicationContextAware {
private ApplicationContext CONTEXT;
public void setApplicationContext(ApplicationContext context) throws BeansException {
CONTEXT = context;
}
public void originalMethod() {
getSpringProxy().doDatabaseStuff()
doNonDatabaseStuff()
}
private DoStuff getSpringProxy() {
return context.getBean(this.getClass());
}
#Transactional
public void doDatabaseStuff() {
...
}
public void doNonDatabaseStuff() {
...
}
}
Explanation:
Make the class ApplicationContextAware, so it has a reference to the context
When you need to call a transactional method, fetch the actual spring proxy from the context
Use this proxy to call your method, so that #Transactional is actually applied.
Your approach looks like it should work just fine, I expect the issue is related to Spring proxies.
The reason that I asked about interfaces is related to the default method by which Spring applies transactional behaviour - JDK dynamic proxies.
If the actual definition of your class is:
public class DoStuff implements Doable {
public void originalMethod() {
}
}
public interface Doable {
public void originalMethod();
}
If this is indeed the structure, when you moved to the new structure Spring is not able to proxy the new doDatabaseStuff method.
Your options to fix this:
Add the new methods to your interface to ensure that Spring can proxy them
Move to using CGLIB based proxies (these do not rely on interfaces)
I am trying to extract the bean from application context.
so I defined class:
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public void setApplicationContext(ApplicationContext _applicationContext) throws BeansException {
applicationContext = _applicationContext;
}
}
and in my applicationContext.xml
<bean id="workflowService" class="com.mycompany.util.WorkflowService">
<bean id="applicationContextProvider" class="com.mycompany.util.ApplicationContextProvider"></bean>
<context:annotation-config />
However in my code when I try:
WorkflowService service = (WorkflowService) ApplicationContextProvider.getApplicationContext().getBean("workflowService");
I get:
java.lang.ClassCastException: $Proxy40 cannot be cast to com.mycompany.util.WorkflowService
EDITED:
WorkflowService code:
public class WorkflowService implements Serializable {
...
#PostConstruct
public void init() {
}
...
#Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public Collection<lData> findData(Integer contractId) {
}
}
I guess WorkflowService is a class implementing at least one interface (you haven't provided enough code). You are trying to lookup the exact class from Spring, while you should ask for one of the interfaces.
This is because Spring most of the time wraps beans in several proxies (e.g. transactional ones). If the class implements at least one interface, resulting proxy implements all of them, but cannot be cast into original class. If the class does not implement any interfaces (commonly considered a bad practice for heavyweight services, questionable though), Spring will use CGLIB subclassing from original class. In this case you code would be valid.
Your problem is this bit:
WorkflowService implements Serializable
Any proxies that Spring generates will implement all of the interfaces that your class does - in this case, Serializable, which is almost certainly not what you want.
What you should do is extract a new interface from WorkflowService, which includes the findData method (let's call it WorkflowOperations). By implementing that interface, you'll then be able to cast to that interface, e.g.
public interface WorkflowOperations {
Collection<lData> findData(Integer contractId);
}
public class WorkflowService implements WorkflowOperations {
...
#PostConstruct
public void init() {
}
...
#Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public Collection<lData> findData(Integer contractId) {
}
}
and then:
WorkflowOperations service = (WorkflowOperations) ApplicationContextProvider.getApplicationContext().getBean("workflowService");
You should probably also remove Serializable from WorkflowService. You almost certainly don't need this, it makes no sense to serialize Spring beans like this. If you just added Serializable out of habit, then remove it (and get out of that particular habit).
You are annotating your service with #Transactional, so Spring is wrapping your service bean with a transactional JDK dynamic proxy that implements the same interfaces as your bean, but is not a WorkflowService. That is why you get a ClassCastException when you try to assign it to a WorkflowService variable. I see two possible solutions:
Specify an interface WorkflowService with your business methods and implement it in a WorkflowServiceImpl class. Then in the Spring context change the bean definition from WorkflowService to WorkflowServiceImpl. This is what I recommend, both as a general design principle and specially to work in a Spring environment: Spring likes interfaces.
In your Spring context, add proxy-target-class="true" to your <tx:annotation-driven/> element in order to force Spring to implement proxies by subclassing, so that proxy instanceof WorkFlowService is true. I find this solution dirtier. Also note that you add a dependency on CGLIB this way.
How i can define one ApplicationContext as prototype spring bean in other application context. Also i need pass current context as parent to new application context.
Details:
I have Bean, that represent one user sessions in rich client application. This class manage lifetime of application context, and few other objects (like database connection). This session beans itself configured by special "start-up application context" .
Now i'm want unit test this session beans, but have trouble because session specific application context created inside session bean, and has many depend to "start-up context";
Example code:
public class UserDBAminSession implements ApplicationContextAware, UserSession {
ApplicationContext startupContext;
ApplicationContext sessionContext;
public void setApplicationContext(ApplicationContext startupContext) {...}
public void start() {
createSessionContext() ;
}
private void createSessionContext() {
sessionContext = new ClassPathXmlApplicationContext("admin-session.xml", startupContext);
}
}
For testing purpose i want relapse createSessionContext function code with something like this:
sessionContext = startupContext.getBean("adminContext", ApplicationContext.class);
Then i can create mock of startupContext, what return some stub. Or even DI "session context" to bean by spring, in some future. But, i don't know how pass parent context parameter to ClassPathXmlApplicationContext constructor. I'm try something like this, but it seems not work:
<bean id="adminContext" class="org.springframework.context.support.ClassPathXmlApplicationContext"
scope="prototype" autowire="constructor">
<constructor-arg type="java.lang.String">
<value>admin-session.xml</value>
</constructor-arg>
</bean>
Also I'm think about create application context on top level and pass it by setter, but:
This just move problem to above level, not solve. In fact it already done (UserSession - are this "top level").
This broke RAII pattern.
This need huge code refactoring.
Or make special "context factory" objects, but it harder already not best code.
What look stupid, I can't IoC objects from IoC framework itself. May be i'm misread some spring documentation?
Any other idea, how unit-test this class?
Use FactoryBean and ApplicationContextAware interfaces.
public class ChildApplicationContextFactoryBean implements FactoryBean, ApplicationContextAware {
protected String[] configLocations;
protected ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
#Override
public Object getObject() throws Exception {
return new ClassPathXmlApplicationContext(configLocations, applicationContext);
}
#Override
public Class getObjectType() {
return ClassPathXmlApplicationContext.class;
}
#Override
public boolean isSingleton() {
return true;
}
public void setConfigLocations(String[] configLocations) {
this.configLocations = configLocations;
}
}
Usage:
<bean class="com.skg.ecg.portal.operation.transit.ChildApplicationContextFactoryBean">
<property name="configLocations">
<list>
<value>applicationContext.xml</value>
</list>
</property>
</bean>
If I understand you correctly, your requirement is for managing a collection of beans within a manually-controlled scope (your RIA session, in this case).
Spring has support for scoped beans. You have the basic singleton and prototype scopes, and webapps get the request and session scopes as well. If your RIA session is actually an HTTP session, then I suggest you use session-scoped beans instead of your manually-nested application context design.
If your sessions are not web-related, then you still have the option of definign your own custom scope. There's more work in this, but it is a defined extension point in the container, so you're on safe ground.
Your original idea of application contexts being themselves beans within a parent context would work, yes, but it's probably unnecessary in this case, and just adds complexity. If you want to investigate it further, however, have a look at the SingletonBeanFactoryLocator, which is a Spring infrastructure class for managing hierarchies of application contexts. It won't do the specific job you want, but it might give you ideas.
Is there a way to statically/globally request a copy of the ApplicationContext in a Spring application?
Assuming the main class starts up and initializes the application context, does it need to pass that down through the call stack to any classes that need it, or is there a way for a class to ask for the previously created context? (Which I assume has to be a singleton?)
If the object that needs access to the container is a bean in the container, just implement the BeanFactoryAware or ApplicationContextAware interfaces.
If an object outside the container needs access to the container, I've used a standard GoF singleton pattern for the spring container. That way, you only have one singleton in your application, the rest are all singleton beans in the container.
You can implement ApplicationContextAware or just use #Autowired:
public class SpringBean {
#Autowired
private ApplicationContext appContext;
}
SpringBean will have ApplicationContext injected, within which this bean is instantiated. For example if you have web application with a pretty standard contexts hierarchy:
main application context <- (child) MVC context
and SpringBean is declared within main context, it will have main context injected;
otherwise, if it's declared within MVC context, it will have MVC context injected.
Here's a nice way (not mine, the original reference is here:
http://sujitpal.blogspot.com/2007/03/accessing-spring-beans-from-legacy-code.html
I've used this approach and it works fine. Basically it's a simple bean that holds a (static) reference to the application context. By referencing it in the spring config it's initialized.
Take a look at the original ref, it's very clear.
I believe you could use SingletonBeanFactoryLocator. The beanRefFactory.xml file would hold the actual applicationContext, It would go something like this:
<bean id="mainContext" class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg>
<list>
<value>../applicationContext.xml</value>
</list>
</constructor-arg>
</bean>
And the code to get a bean from the applicationcontext from whereever would be something like this:
BeanFactoryLocator bfl = SingletonBeanFactoryLocator.getInstance();
BeanFactoryReference bf = bfl.useBeanFactory("mainContext");
SomeService someService = (SomeService) bf.getFactory().getBean("someService");
The Spring team discourage the use of this class and yadayada, but it has suited me well where I have used it.
Before you implement any of the other suggestions, ask yourself these questions...
Why am I trying to get the ApplicationContext?
Am I effectively using the ApplicationContext as a service locator?
Can I avoid accessing the ApplicationContext at all?
The answers to these questions are easier in certain types of applications (Web apps, for example) than they are in others, but are worth asking anyway.
Accessing the ApplicationContext does kind of violate the whole dependency injection principle, but sometimes you've not got much choice.
SpringApplicationContext.java
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Wrapper to always return a reference to the Spring Application
Context from
* within non-Spring enabled beans. Unlike Spring MVC's
WebApplicationContextUtils
* we do not need a reference to the Servlet context for this. All we need is
* for this bean to be initialized during application startup.
*/
public class SpringApplicationContext implements
ApplicationContextAware {
private static ApplicationContext CONTEXT;
/**
* This method is called from within the ApplicationContext once it is
* done starting up, it will stick a reference to itself into this bean.
* #param context a reference to the ApplicationContext.
*/
public void setApplicationContext(ApplicationContext context) throws BeansException {
CONTEXT = context;
}
/**
* This is about the same as context.getBean("beanName"), except it has its
* own static handle to the Spring context, so calling this method statically
* will give access to the beans by name in the Spring application context.
* As in the context.getBean("beanName") call, the caller must cast to the
* appropriate target class. If the bean does not exist, then a Runtime error
* will be thrown.
* #param beanName the name of the bean to get.
* #return an Object reference to the named bean.
*/
public static Object getBean(String beanName) {
return CONTEXT.getBean(beanName);
}
}
Source: http://sujitpal.blogspot.de/2007/03/accessing-spring-beans-from-legacy-code.html
If you use a web-app there is also another way to access the application context without using singletons by using a servletfilter and a ThreadLocal. In the filter you can access the application context using WebApplicationContextUtils and store either the application context or the needed beans in the TheadLocal.
Caution: if you forget to unset the ThreadLocal you will get nasty problems when trying to undeploy the application! Thus, you should set it and immediately start a try that unsets the ThreadLocal in the finally-part.
Of course, this still uses a singleton: the ThreadLocal. But the actual beans do not need to be anymore. The can even be request-scoped, and this solution also works if you have multiple WARs in an Application with the libaries in the EAR. Still, you might consider this use of ThreadLocal as bad as the use of plain singletons. ;-)
Perhaps Spring already provides a similar solution? I did not find one, but I don't know for sure.
Take a look at ContextSingletonBeanFactoryLocator. It provides static accessors to get hold of Spring's contexts, assuming they have been registered in certain ways.
It's not pretty, and more complex than perhaps you'd like, but it works.
There are many way to get application context in Spring application. Those are given bellow:
Via ApplicationContextAware:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class AppContextProvider implements ApplicationContextAware {
private ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
Here setApplicationContext(ApplicationContext applicationContext) method you will get the applicationContext
ApplicationContextAware:
Interface to be implemented by any object that wishes to be notified
of the ApplicationContext that it runs in. Implementing this interface
makes sense for example when an object requires access to a set of
collaborating beans.
Via Autowired:
#Autowired
private ApplicationContext applicationContext;
Here #Autowired keyword will provide the applicationContext. Autowired has some problem. It will create problem during unit-testing.
Note that by storing any state from the current ApplicationContext, or the ApplicationContext itself in a static variable - for example using the singleton pattern - you will make your tests unstable and unpredictable if you're using Spring-test. This is because Spring-test caches and reuses application contexts in the same JVM. For example:
Test A run and it is annotated with #ContextConfiguration({"classpath:foo.xml"}).
Test B run and it is annotated with #ContextConfiguration({"classpath:foo.xml", "classpath:bar.xml})
Test C run and it is annotated with #ContextConfiguration({"classpath:foo.xml"})
When Test A runs, an ApplicationContext is created, and any beans implemeting ApplicationContextAware or autowiring ApplicationContext might write to the static variable.
When Test B runs the same thing happens, and the static variable now points to Test B's ApplicationContext
When Test C runs, no beans are created as the TestContext (and herein the ApplicationContext) from Test A is resused. Now you got a static variable pointing to another ApplicationContext than the one currently holding the beans for your test.
Not sure how useful this will be, but you can also get the context when you initialize the app. This is the soonest you can get the context, even before an #Autowire.
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
private static ApplicationContext context;
// I believe this only runs during an embedded Tomcat with `mvn spring-boot:run`.
// I don't believe it runs when deploying to Tomcat on AWS.
public static void main(String[] args) {
context = SpringApplication.run(Application.class, args);
DataSource dataSource = context.getBean(javax.sql.DataSource.class);
Logger.getLogger("Application").info("DATASOURCE = " + dataSource);
I use a simple, standardized way to allow external access to any of my own singleton Spring Beans. With this method, I continue to let Spring instantiate the Bean. Here's what I do:
Define a private static variable of the same type as the enclosing class.
Set that variable to this in each of the class's constructors. If the class has no constructors, add a default constructor in which to set the variable.
Define a public static getter method that returns the singleton variable.
Here's an example:
#Component
public class MyBean {
...
private static MyBean singleton = null;
public MyBean() {
...
singleton = this;
}
...
public void someMethod() {
...
}
...
public static MyBean get() {
return singleton;
}
}
I can then call someMethod on the singleton bean, anywhere in my code, via:
MyBean.get().someMethod();
If you are already subclassing your ApplicationContext, you can add this mechanism to it directly. Otherwise, you could either subclass it just to do this, or add this mechanism to any bean that has access to the ApplicationContext, and then use it to gain access to the ApplicationContext from anywhere. The important thing is that it is this mechanism that will let you get into the Spring environment.
Approach 1: You can inject ApplicationContext by implementing ApplicationContextAware interface. Reference link.
#Component
public class ApplicationContextProvider implements ApplicationContextAware {
private ApplicationContext applicationContext;
public ApplicationContext getApplicationContext() {
return applicationContext;
}
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
Approach 2: Autowire Application context in any of spring managed beans.
#Component
public class SpringBean {
#Autowired
private ApplicationContext appContext;
}
Reference link.
Do autowire in Spring bean as below:
#Autowired
private ApplicationContext appContext;
You will get the ApplicationContext object.
Please note that; the below code will create new application context instead of using the already loaded one.
private static final ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
Also note that beans.xml should be part of src/main/resources means in war it is part of WEB_INF/classes, where as the real application will be loaded through applicationContext.xml mentioned at Web.xml.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>META-INF/spring/applicationContext.xml</param-value>
</context-param>
It is difficult to mention applicationContext.xml path in ClassPathXmlApplicationContext constructor. ClassPathXmlApplicationContext("META-INF/spring/applicationContext.xml") wont be able to locate the file.
So it is better to use existing applicationContext by using annotations.
#Component
public class OperatorRequestHandlerFactory {
public static ApplicationContext context;
#Autowired
public void setApplicationContext(ApplicationContext applicationContext) {
context = applicationContext;
}
}
I know this question is answered, but I would like to share the Kotlin code I did to retrieve the Spring Context.
I am not a specialist, so I am open to critics, reviews and advices:
https://gist.github.com/edpichler/9e22309a86b97dbd4cb1ffe011aa69dd
package com.company.web.spring
import com.company.jpa.spring.MyBusinessAppConfig
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import org.springframework.stereotype.Component
import org.springframework.web.context.ContextLoader
import org.springframework.web.context.WebApplicationContext
import org.springframework.web.context.support.WebApplicationContextUtils
import javax.servlet.http.HttpServlet
#Configuration
#Import(value = [MyBusinessAppConfig::class])
#ComponentScan(basePackageClasses = [SpringUtils::class])
open class WebAppConfig {
}
/**
*
* Singleton object to create (only if necessary), return and reuse a Spring Application Context.
*
* When you instantiates a class by yourself, spring context does not autowire its properties, but you can wire by yourself.
* This class helps to find a context or create a new one, so you can wire properties inside objects that are not
* created by Spring (e.g.: Servlets, usually created by the web server).
*
* Sometimes a SpringContext is created inside jUnit tests, or in the application server, or just manually. Independent
* where it was created, I recommend you to configure your spring configuration to scan this SpringUtils package, so the 'springAppContext'
* property will be used and autowired at the SpringUtils object the start of your spring context, and you will have just one instance of spring context public available.
*
*Ps: Even if your spring configuration doesn't include the SpringUtils #Component, it will works tto, but it will create a second Spring Context o your application.
*/
#Component
object SpringUtils {
var springAppContext: ApplicationContext? = null
#Autowired
set(value) {
field = value
}
/**
* Tries to find and reuse the Application Spring Context. If none found, creates one and save for reuse.
* #return returns a Spring Context.
*/
fun ctx(): ApplicationContext {
if (springAppContext!= null) {
println("achou")
return springAppContext as ApplicationContext;
}
//springcontext not autowired. Trying to find on the thread...
val webContext = ContextLoader.getCurrentWebApplicationContext()
if (webContext != null) {
springAppContext = webContext;
println("achou no servidor")
return springAppContext as WebApplicationContext;
}
println("nao achou, vai criar")
//None spring context found. Start creating a new one...
val applicationContext = AnnotationConfigApplicationContext ( WebAppConfig::class.java )
//saving the context for reusing next time
springAppContext = applicationContext
return applicationContext
}
/**
* #return a Spring context of the WebApplication.
* #param createNewWhenNotFound when true, creates a new Spring Context to return, when no one found in the ServletContext.
* #param httpServlet the #WebServlet.
*/
fun ctx(httpServlet: HttpServlet, createNewWhenNotFound: Boolean): ApplicationContext {
try {
val webContext = WebApplicationContextUtils.findWebApplicationContext(httpServlet.servletContext)
if (webContext != null) {
return webContext
}
if (createNewWhenNotFound) {
//creates a new one
return ctx()
} else {
throw NullPointerException("Cannot found a Spring Application Context.");
}
}catch (er: IllegalStateException){
if (createNewWhenNotFound) {
//creates a new one
return ctx()
}
throw er;
}
}
}
Now, a spring context is publicly available, being able to call the same method independent of the context (junit tests, beans, manually instantiated classes) like on this Java Servlet:
#WebServlet(name = "MyWebHook", value = "/WebHook")
public class MyWebServlet extends HttpServlet {
private MyBean byBean
= SpringUtils.INSTANCE.ctx(this, true).getBean(MyBean.class);
public MyWebServlet() {
}
}
Even after adding #Autowire if your class is not a RestController or Configuration Class, the applicationContext object was coming as null. Tried Creating new class with below and it is working fine:
#Component
public class SpringContext implements ApplicationContextAware{
private static ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws
BeansException {
this.applicationContext=applicationContext;
}
}
you can then implement a getter method in the same class as per your need like getting the Implemented class reference by:
applicationContext.getBean(String serviceName,Interface.Class)