Spring Context and Autowire configuration to copy production to test? - java

I need to write a utility that copies data from a Production to a Test environment to prepare a database for testing the application prior to a large refactoring.
I really need to re-use the existing application config files unchanged, so that I don't find myself refactoring prior to establishing a testing baseline.
My first attempt is to try to instantiate the same beans with different configuration contexts corresponding to each environment.
Here is my first attempt:
public class PrepareDatabase {
#Component
static class Context {
#Autowired UserInfoSecurity userSec;
#Autowired UserDao userDao;
}
public static void main(String[] args) {
try(ClassPathXmlApplicationContext prodContext =
new ClassPathXmlApplicationContext("classpath:/prod/web-client-env.xml");
ClassPathXmlApplicationContext testContext =
new ClassPathXmlApplicationContext("classpath:/test/web-client-env.xml")) {
Context prod = prodContext.getBean(Context.class);
Context test = testContext.getBean(Context.class);
Stream<UserDso> users = prod.userDao.scan().map(prod.userSec::sanitize);
test.userDao.batchPutItems(users);
}
}
}
This fails with No qualifying bean of type '...PrepareDataba se$Context' available
I think I understand what's happening: the PrepareDatabase class is not being scanned.
But how can I fix this? I am not confident that this is even the right approach to begin with.

Got it working by switching to AnnotationConfigApplicationContext.
The relevant section of code looks like this:
try(AnnotationConfigApplicationContext prodContext =
new AnnotationConfigApplicationContext();
AnnotationConfigApplicationContext testContext =
new AnnotationConfigApplicationContext()) {
System.setProperty("config_path", "classpath:/prod");
prodContext.register(MyApp.class);
prodContext.refresh();
System.setProperty("config_path", "classpath:/test");
testContext.register(MyApp.class);
testContext.refresh();
Context prod = prodContext.getBean(Context.class);
Context test = testContext.getBean(Context.class);
YMMV - in my case the config_path variable is used in various places already to import the correct environment-specific files with something like this
<import resource="${config_path}/some_file_name.xml"/>
and this
#PropertySources({#PropertySource("${config_path}/backend.properties"),

Related

Other ways to create a Bean Factory in Spring Framework

I understand the difference between a BeanFactory and an ApplicationContext.
I am also aware that a BeanFactory instance can be created from xml files, which reside in the classpath or anywhere else in the file system. So, an XMLBeanFactory instance is created in such cases.
At the same time, I was digging into BeanFactory documentation and stumbled upon this.
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/BeanFactory.html
Normally a BeanFactory will load bean definitions stored in a configuration source (such as an XML document), and use the org.springframework.beans package to configure the beans. However, an implementation could simply return Java objects it creates as necessary directly in Java code. There are no constraints on how the definitions could be stored: LDAP, RDBMS, XML, properties file, etc. Implementations are encouraged to support references amongst beans (Dependency Injection).
So, does this mean that the bean definition can be in non-XML format as well? viz, LDAP, RDBMS, properties file etc? If yes, please provide an snippet of it. I am exclusively looking for BeanFactory only and not any ApplicationContext implementations.
How to load an ApplicationContext which is a BeanFactory on steriods is explained in this blog.
public class SpringContextsApplication {
public static void main(String[] args) throws Exception {
GenericApplicationContext contextFromProperties =
new GenericApplicationContext();
BeanDefinitionReader reader =
new PropertiesBeanDefinitionReader(contextFromProperties);
reader.loadBeanDefinitions("classpath:application-context.properties");
contextFromProperties.refresh();
doGreeting(contextFromProperties);
contextFromProperties.stop();
}
private static void doGreeting(ApplicationContext ctx) {
Greeter greeter = ctx.getBean(Greeter.class);
Person person = ctx.getBean(Person.class);
greeter.greet(person);
}
}
Where there is a GenericApplicationContext one could also use a DefaultListableBeanFactory instead and achieve the same result.
public class SpringContextsApplication {
public static void main(String[] args) throws Exception {
GenericApplicationContext contextFromProperties =
new DefaultListableBeanFactory();
BeanDefinitionReader reader =
new PropertiesBeanDefinitionReader(contextFromProperties);
reader.loadBeanDefinitions("classpath:application-context.properties");
doGreeting(contextFromProperties);
contextFromProperties.stop();
}
private static void doGreeting(BeanFactory ctx) {
Greeter greeter = ctx.getBean(Greeter.class);
Person person = ctx.getBean(Person.class);
greeter.greet(person);
}
}
To load bean definitions one needs a BeanDefinitionReader for that specific implementation you want to use. Here that is property files but you could write a BeanDefinitionReader for LDAP, JDBC, YAML etc. as well.
Spring supports out-of-the-box
XML
Properties (Deprecated as of Spring 5.3, propably removed in Spring 6)
Groovy
Java Classes
JDBC (Purely as an exampled, deprecated in 5.3 and removed in Spring 6)
However you can create whatever implementation you like if you need.

Spring integration test with custom application context

For my application I created my own type of ApplicationContext that allows me to interact in specific manners that are needed for may application. As the application is a desktop application, I create the context like this:
#SpringBootApplication
#Import(StandaloneConfiguration.class)
#PropertySource(value = {"application.properties", "server.properties"})
public class OpenPatricianApplication extends Application {
private ApplicationContext context;
#Override
public void init() {
SpringApplicationBuilder builder = new SpringApplicationBuilder(OpenPatricianApplication.class);
context = builder.contextClass(DependentAnnotationConfigApplicationContext.class).run(getParameters().getRaw().toArray(new String[0]));
// more initialisation
}
}
}
Now I want to create a Spring Boot integration test that actually relies on the functionality of my own ApplicationConext implementation.
#SpringBootTest(classes = {ServerTestConfiguration.class})
public class ServerIntegrationTest {
private DependentAnnotationConfigApplicationContext context;
}
How do I go about initializing my context in the test? The context must be created in order to start the spring application for this to work, but with the SpringBootTest annotation this already happened, when the constructor is entered.
Are there any additional annotations or parameter for existing ones that can be applied? Should tests of these nature not be annotated with SpringBootTest at all and the application created manually?
The approach that I found to solve this issue is to forgo the SpringBootTest annotation altogether and construct the context as part of the constructor. Alternatively you could also do it in the BeforeAll or BeforeEach method, but as my test class extends a base class that needs some beans injected, the constructor seemed the right choice.
However what does not work is injecting the beans in the super class by way of constructor injection, as the call to the super constructor has to be the first call in the constructor and that would necessitate to have a static initializer block for the context and I want to avoid static stuff as much as possible, especially if the context is not properly cleaned up at the end of the test, it would live on as part of the loaded class in memory and potentially consume lot of memory.
So here is the code:
public class ServerIntegrationTest extends SaveLoadBase<CityWall> {
public CityWallSerializationTest() {
SpringApplicationBuilder builder = new SpringApplicationBuilder(ServerTestConfiguration.class);
DependentAnnotationConfigApplicationContext context = (DependentAnnotationConfigApplicationContext) builder.contextClass(DependentAnnotationConfigApplicationContext.class).run();
setContext(context);
setClientServerEventBus((AsyncEventBus) context.getBean("clientServerEventBus"));
setLoadAndSaveService(context.getBean(TestableLoadAndSaveService.class));
}
}

How can I test an old Spring 2.0.7 application with JUnit?

I have an old app built with an ancient version of Spring: 2.0.7. I have been tasked with adding new functionality to this app, so I'm required to write some JUnit tests too.
So far, I have writen mockup classes for my services, and an applicationContext-test.xml file placed under src/test/resources/. Typically, the next step would be to write my test case like this:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"/applicationContext-test.xml"})
public class MyTestCase {
...
}
But as I read, the Spring TestContext Framework was first introduced in Spring 2.5, and therefore it's not available to me.
Is there any other way in which I can load the applicationContext.xml file within JUnit, and access the beans defined in that XML file?
Since I already have the mockups and they don't require initialization parameters, I could just instantiate them and pass them to the setter, maybe using the #BeforeClass annotation. But I would prefer using the Spring context, if possible, given that I ended up with a somehow unusual way to load the beans and it should be tested too...
I ended writing an ApplicationContext wrapper, and calling the init method myself with a #Before annotation, instead of relying on Spring to do that. This way, I can test my initialization method as if it was called from Spring.
public class ApplicationContextMock implements ApplicationContext {
private Map<String, Object> beans;
public ApplicationContextMock() {
beans = new HashMap<String, Object>();
beans.put("child1", new SomeServiceMock());
beans.put("child2", new AnotherServiceMock());
}
public Object getBean(String arg0) throws BeansException {
return beans.get(arg0);
}
// ...
}
#RunWith(JUnit4.class)
public class MyTestCase {
MyClass foo;
#Before
public void init() {
foo = new MyClass();
foo.loadChildren(new ApplicationContextMock());
}
// ...
}
(I still want to know if there is a better way of doing this, without the Spring 2.5+ annotations).

Spring- How to use Spring Dependency Injection to write a Standalone Java Application

I want to write a standalone application with IOC, how do I use springs dependency injection in there? I'm using JIdea. There is spring 2.5 support but I want to use spring 3.0 here is the way I tried!
I experience in using Spring MVC we can inject dependencies there in a WebApplicationContext but how do I inject dependencies in a standalone application
I tried this
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"com\\ttg\\xmlfile.xml"});
but I cannot see that the dependencies are injected by the beans defined there (in the XML file)
I put the above code in the main method and two bean definitions for two Objects,in one Java class's constructor I used the other class's object - which was injected to this object - and called a method on that which will print some thing but it didn't worked I thought that the above code creates all the dependencies and injects them but it doesn't seem like that
How do I properly use Springs IOC, dependency injection in my stand alone app which does not contain a WebApplicationContext?
Please mention steps.
suppose you have:
class Bean1 {
Bean2 bean2;
}
class Bean2 {
String data;
}
the context.xml file
<bean id="bean1" class="Bean1">
<property name="bean2" ref="bean2" />
</bean>
<bean id="bean2" class="Bean2" />
then this should be true
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"context.xml"});
Bean1 bean1 = (Bean1) context.getBean("bean1");
// bean1.bean2 should not be null here.
you can use autowiring support provided by spring, in order to inject dependencies (and possibly apply post processors) to an object that is not part of the application context.
In your case, this object is your standalone application.
Here is the way to achieve this. In this example, I use #Autowired (for b1), traditional DI (for b2) and initialization hook for b3. The autowiring support with annotations assumes you have defined the appropriate spring post-processor in your application context (e.g. by declaring <context:annotation-config/>).
public class StandaloneApp implements InitializingBean {
#Autowired private Bean1 b1;
private Bean2 b2;
private Bean3 b3;
public void afterPropertiesSet() throws Exception {
this.b3 = new Bean3(b1, b2);
}
public void setB2(Bean2 b2) {
this.b2 = b2;
}
public static void main(String... args) {
String[] locations = // your files relative to the classpath
ApplicationContext ac = new ClasspathXmlApplicationContext(locations);
// or use FileSystemXmlApplicationContext if the files are not in the classpath
StandaloneApp app = new StandaloneApp();
AutowireCapableBeanFactory acbf = ac.getAutowireCapableBeanFactory();
acbf.autowireBeanProperties(app, AUTOWIRE_BY_NAME, false);
acbf.initializeBean(app, "standaloneApp"); // any name will work
}
}
In this example, all b1, b2 and b3 should be non-null (assuming b1 and b2 beans exist in your application context).
I haven't tested it (might not even compile due to some typo), but the idea is in the last 3 lines. See the javadocs for AutowireCapableBeanFactory and mentionned methods to see exactly what happens.
If you prefer (mostly) pure java, you can use java config:
#Configuration
pubic class MyConfig {
#Bean
public Bean1 bean1() { return new Bean1(); }
#Bean
public Bean2 bean2() { return new Bean2(bean1()); }
}
And then to instantiate:
ApplicationContext ctx =
new AnnotationConfigApplicationContext(MyConfig.class);
Keep in mind there's some things that pure annotation driven configuration doesn't yet support (such as things like tx:annotation-driven), which you might need some xml glue code for.
<beans>
<tx:annotation-driven />
<context:annotation-config/>
<bean class="MyConfig"/>
</beans>
And then use a standard xml based way of creating the ApplicationContext (like ClasspathXmlApplicationContext, or the spring web context loader, etc...).
How did you confirm that your beans aren't being wired correctly? One common issue is the xml config file not being in the right place. Can you give us some more information like your project layout and the code you use to obtain the beans from the container?
If you add log4j logging to your app, you should see a cascade of messages coming out that will tell you a lot about what Spring is and is not doing. If you don't have that feedback, you're in the dark. You might be able to ferret out the answer just by getting more information out of Spring from log4j.
Are you calling context.getBean("beanName") to get a reference to the bean or are you doing a new SomeClass()? If you do it through getBean() then the injected properties should be set.
Also, be sure to use the same bean factory (ClassPathXmlApplicationContext instance) for retrieving all your beans. This should most likely be static final and used by the entire application.
you can use the command #Autowired

Getting Spring Application Context

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)

Categories