Spring NON MVC project configuration - Best Practices - java

I am going to work on a Java project and want to use Spring IOC for bean management.
This is not a web project but just a simple java project that will give me a jar file at the end.
My questions is that, in my application i want to use Spring IoC to get instances of classes to call their respective methods. For the purpose i need to get the spring context using
CalenderDao calenderDao = (CalenderDao) ApplicationContextUtils
.getApplicationContext().getBean("calenderDao");
calenderDao.getCalenderUpdate();
Now if i need this bean in some other class too , i will copy and paste the same thing there as well like.
CalenderDao calenderDao = (CalenderDao) ApplicationContextUtils
.getApplicationContext().getBean("calenderDao");
calenderDao.getCalenderUpdate();
My question here is that, do i need to create a ApplicationContext in each file to get a bean throughout the application. Or is there any alternate and best thing to perform. And if i am doing the thing like this way how can use setter injection or constructor injection in application.
In web apps this is quit simple we loads the context one time and everything works fine, but how to do this in non web where we don't have web.xml file to instantiate the context.
Please help how beans are managed in non web project using spring.

Spring is not just designed for web apps.
Just because it's not a web application you dont need to fall back to "provider style". You do not need a web.xml to initialize an application context.
Use your main method to create an application context and work with your beans as you would do for a webapp. You can use autowiring and all the gadgets of spring.
Once the context is initialized call your main class to start your application, for example with the help of the refresh event. From there on you have (almost) no need to use getBean.
Obviously you dont have session and request scope, but singleton and prototype are available.
Just take a look at the spring docs.

Wherever you require ApplicationContext in your application, implement that class with ApplicationContextAware interface.
Say here
public class CalenderService implements ApplicationContextAware{
private ApplicationContext context;//declare this so you can use it
}
As it is interface you need to overide its method
public void setApplicationContext(ApplicationContext context){
this.context=context; // here ApplicationContext gets injected.
}

Related

I am build a common jar to be used by both spring boot and a J2EE application

I have a common project I'd like to import to both a spring boot application and a J2EE application. One of the Objects is a set of attributes set from parameters. In spring boot I'd like to use #Value to set them, for the non-spring platform I have to load the properties with code. I'd like to use the same object for both environments since it's use is pervasive. My attempts to use builders have failed because they inevitably get instantiated before the spring objects.
Who's done this?
Thanks in advance
I'd hoped for something more elegant but maybe I'm spoiled by Spring Boot. I had to replace the #Autowired parameters class with a builder that implements ApplicationContextAware. The setApplicationContext method will instantiate the parameters object if it gets executed (the builder class was loaded by Spring and is aware) or by the simple retrieval of parameters for a non-spring environment.

How is Spring Container created?

I am studying for the Spring Core certification and I have following doubt about this question:
What is meant by “container” and how do you create one?
I know that the Spring container is at the core of the Spring Framework. The container will create the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application. These objects are called Spring Beans which we will discuss in next chapter.
And I know that there exist 2 containers:
Spring BeanFactory Container: This is the simplest container providing basic support for DI and defined by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purposes of backward compatibility with the large number of third-party frameworks that integrate with Spring.
Spring ApplicationContext Container: This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by the org.springframework.context.ApplicationContext interface.
Ok...this is pretty clear for me but what is the correct answer about How to create a container?
I think that it is automatically created by the Spring when it reads the configuration class or the XML configuration file.
Or not? What am I missing?
In short, "The Container" is a Spring instance in charge of managing the lifecycle of your beans.
To create one, basically, you should do something like
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/application-context.xml");
Remember replacing /application-context.xml by the file where you define your own Spring beans.
Take a look at http://www.springbyexample.org/examples/intro-to-ioc-creating-a-spring-application.html
You could also substitute the xml by a configuration class. On that case you should have something like this:
#Configuration
public class Myconfig{
#Bean
public MyBean myBean(){
return new MyBean();
}
}
For this, take a look at http://www.tutorialspoint.com/spring/spring_java_based_configuration.htm

How to get ServletConfig within Spring application?

try to autowired ServletConfig into current application, not ServletContext because an API ask for it.
I know user can get ServletContext by a ServletConfig servlet but how to do the other way around or taken from spring application
Rather than autowiring, trying implementing ServletConfigAware.
Edit:
I couldn't find an example that shows using ServletConfigAware in a real project. Essentially, you'd have a class that implemented this interface to obtain the ServletConfig.
You'd create a Spring bean from the class by annotating the class with #Component or declaring a bean in XML. When Spring creates the bean, it would invoke setServletConfig(ServletConfig servletConfig).
Once you had an instance of ServletConfig in your bean, you'd do whatever you need with it.
Your question was how to obtain the ServletConfig, but I think (correct me if I'm wrong) you are looking to integrate a legacy Servlet into your Spring Web MVC application. ServletWrappingController might be a better choice. I haven't ever used it myself, but it appears to be specifically designed for that purpose.

Access ServletContext resources in CDI Extension

I'm facing the following situation: I have written a CDI extension, with which I want to programatically register additional beans into the BeanManager. I've already implemented the extension and registered in in the META-INF/services folder. Everything works fine so far and I can trace the container calling this method:
public class TestCdiExtension implements Extension {
public void observeAfterBeanDiscovery(#Observes AfterBeanDiscovery event, BeanManager manager) {
// Code goes here
}
}
My problem now is this: To determine which beans should be registered, I need access to the ServletContext of the current web application in which CDI is running.
I understand that you can use CDI completely without a servlet environment, so there is no hard link. However: How can I do the job of registering additional beans depending on what's in the ServletContext?
Is using an extension the correct way at all? Is there any other (better?) solution of doing this?

Implementing servlet lifecycle methods in a Spring web application?

I am implementing a web application using Spring. I am using Spring's ContextLoaderListener, to load up my application contexts, and Spring's DispatcherServlet, to load the relevant beans from {name}-servlet.xml, which refer to the beans in the main application context. I want to be able to integration test these Spring configurations outside of the container to validate everything is wired up correctly before I deploy to Tomcat. However my application requires some scheduled background processing when running in the container. In a regular HttpServlet I would simply implement init() and destroy(). All the suggestions I have read suggest using an InitializingBean for that kind of initialization.
However, if I use an InitializingBean, afterPropertiesSet() gets called whether I am inside the container or in integration tests - and outside the container, I don't have access to the resources that background task needs. Is there a better way to perform the tasks I would normally perform in init() and destroy() so that they will only run when deployed as a webapp?
Have you considered using a test spring config file that overrides the bean implementing your background process?
This way everything else in the spring configuration would work normally except for the one overridden bean.

Categories