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.
Related
I am a beginner of Spring and I still can't understand clearly what Bean is. From its definition, it seems a object that is determined by some pre-set configuration files or using annotation on a class. Once the spring starts up, the bean has been created. But can Spring use DI to create some instances of which attributes are not pre-determined?(Like, a user posts a json from website to Spring. And this json contains some data that are used to new a instance. Can Spring use this json to create the instance by using DI?)
Bean is just the object created by your spring application. As you know any spring application has several interacting objects working together to give rise to the desired programmed behavior.
A Bean is basically a managed object i.e at run time the IOC container creates the bean object based on its definition supplied by the coder or as configured in the apllicationContext.xml file under beans tag, and injects it to other classes as required.
Any Spring application is basically a conglomeration of various objects interacting with each other, these objects or beans collaborate to create the application.
A Bean's lifecycle is managed by the Spring IOC container.
The JSON consumed by the Spring Application is taken care of by the HttpMessageConverter. When recieving a new request, the Spring framework will use the content-type header to determine the media type of the request.
It will then try to find the corresponding converter, available in the classpath of the application, to convert the Request body.
Thus its clear that the incoming request body object is not managed by the Spring IOC container and hence is not a Bean.
But these deserialized instances are used as Data Transfer Objects in a Spring application's various layers like, service, DAO, controller.
Spring beans are the objects that comprise your application and are managed by the Spring framework. Comparing them to the concepts of JavaBeans and POJOs provides some explanatory context, and the Spring reference documentation contains extensive documentation of Spring beans, including this summary:
A bean definition essentially is a recipe for creating one or more
objects. The container looks at the recipe for a named bean when
asked, and uses the configuration metadata encapsulated by that bean
definition to create (or acquire) an actual object.
Also included in the reference documentation are descriptions of various ways to instantiate beans via an xml-based or annotation-based configuration approach as well as the Java Config approach (which also uses annotations). This is managed by the Spring BeanFactory interface (API here; source here).
The #Bean annotation is used to indicate that a method instantiates,
configures and initializes a new object to be managed by the Spring
IoC container. For those familiar with Spring’s XML
configuration the #Bean annotation plays the same role as the
element. You can use #Bean annotated methods with any Spring
#Component, however, they are most often used with #Configuration
beans.
You refer in the question to Dependency Injection (DI), a design pattern based on the Inversion of Control principle, which is a critical part of the Spring Framework, particularly for bean instantiation. DI allows values to be passed into the object from outside. The Spring documentation describes both the constructor-based and setter-based approaches to DI provided by the Spring IoC container for instantiating objects (beans).
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
Could you please list all possible sources of getBean?
BTW, If I just write context.getBean(SomeInterface.class), can I get the implementation of the interface class?
They come from the Spring application context (which is what you are calling the getBean method on).
Spring has this concept of an application context, which is an object that contains things such as all the beans managed by Spring.
You put beans in the application context by configuring them in a Spring XML configuration file or by annotating classes with annotations such as #Component, #Service etc. and then letting Spring find them by scanning packages for those classes.
If you write context.getBean(SomeInterface.class) and there is a Spring bean that implements that interface, then that method call will return the bean that implements the interface.
These are basic concepts of the Spring framework. See chapter 5, The IoC Container in the Spring documentation for a detailed explanation of how it works.
If you go into the ApplicationContext class hierarchy, you will find that all spring Application Context file are child of org.springframework.core.io.DefaultResourceLoader class.
What DefaultResourceLoader does is it get the current thread context class loader(if none is provided). So we can understand that all application context file first load the classes defined. Application Context load all the beans defined in xml file, marked using #Bean annotation or other available spring annotations. Once the context scan through the annotation and/ or xml and load all the beans in the class loader. Context first create the dependencies and inject them in dependent.
To get context.getBean(SomeInterface.class), please refer below documentation.
http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/context/support/AbstractApplicationContext.html#getBean(java.lang.Class)
As per my understanding of documentation, you shall get the bean if exact one implementation bean class is defined.
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.
}
I have a JSF session scope bean and I'm keeping current user(logged in) information in that bean. I also have a class which is neither servlet nor bean, its just a class. I want to access the jsf bean and get current user information in the class. I've found a solution for servlet to access jsf bean but i couldnt find a solution for this problem. Is there any way to do that?
Thank!
If the instance of the mentioned class is running in the same thread as the HTTP request thread which has invoked the FacesServlet, then you can just get it by the FacesContext and then Application#evaluateExpressionGet(). See also Get JSF managed bean by name in any Servlet related class
If the instance of the mentioned class is running in a different thread, then you'd need to pass the desired information beforehand to the class' constructor, method or to store the desired information in some shared datasource which both the JSF webapp and the standalone class have access to, such as a database, a local disk file system file or the JNDI context. Depending on the context and the environment, CDI's #Named+#Inject may also be the solution.
The "best way" depends on the concrete functional requirement which is not clear from the question, so I can't point out the right way nor give any kickoff examples.