Why isn't my spring component accessible to the WebApplicationContext? - java

I have a spring component which was used as a flex-blazeds endpoint (using #RemotingDestination) and I now need to reuse it as a REST endpoint.
What I did was create an additional rest servlet (of type DispatcherServlet of courser) in addition to the existing blaze-ds servlet I had.
I then wanted to access the same components using REST (hence my previous question) and I found that I'm getting a 404.
My rest-servlet.xml configuration file looked something like:
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonConverter" />
</list>
</property>
</bean>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>
And my ContextLoaderListener uses all my spring context files, which included the compontent-scan of those components.
Since the flex-servlet had no problem accessing these #Component beans which were scanned by the global context I assumed that the rest-servlet will also had access to them and I just need to add the annotations to the components.
The strange part was that when I explicitely added the component-scan for the package where these components reside then the rest call worked.
This meant that these component beans were being created twice, once for the global context (as it scans a config file containing this scan for the flex servlet) and one for the rest-servlet context (I verified this with a simple static counter and a lock on the class).
My question is why can't the rest-servlet see the beans the flex-servlet can?

While it's true that the servlet appcontext can access the beans from the ContextLoaderListener appcontext, those beans will not be consulted when mapping HTTP calls to controllers. All controller beans must be declared (or scanned) directly in the servlet's appcontext, else they will be ignored.
I suggest that you separate the REST entry point annotations (i.e. #RequestMapping) from your BlazeDS ones. For example, take your UserService class from your other post: create a UserController class, put the REST annotations on that, and delegate from UserController to UserService. UserController would be declared in the servlet app context, and injected with the UserService from the ContextLoaderListener context.

You need to use Spring Web context and define a DispatcherServlet, which will be a child context for the one loaded by ContextLoaderListener.
It is DistpatcherServlet that should load your rest-servlet.xml, not ContextLoaderListener. Otherwise, the guys whom you call "servlets" and who, in fact, I assume, are controllers, just won't get the requests from your client.
You can read about all this stuff here: http://static.springsource.org/spring/docs/3.1.0.RC1/spring-framework-reference/html/mvc.html
This is a standard way of doing Web-related things in Spring, and you definetely need to follow it.

Related

Wiring Database Object with Spring Bean

From Spring in Action book, there is an example of Spring Bean. It uses Compact Disc analogy. When an application needs a "The Beatles" album, it creates "The Beatles" album bean, and as well as other albums.
If there are n albums in database, so should I create n album beans?
If it is not, how the n albums represented in application? Is it just a POJO domain model (not a bean)?
What is the real use case using Spring Bean?
If I were you, I would depart from the analogy of the compact disc as a Spring bean, especially with respect to your later questions. Quite plainly, any Java object can be declared as a bean in Spring, whether you're using XML configuration or Java configuration.
Let's suppose I have these 2 classes:
public class Foo {
private String s;
private Bar bar;
// getters & setters
}
public class Bar {
private int i;
// getter & setter
}
I can make the former a Spring Bean by declaring it in an XML configuration file:
<bean id="foo" class="demo.Foo">
<property name="s" value="Hello, World!" />
<property name="bar">
<bean class="demo.Bar">
<property name="i" value="10" />
</bean>
</property>
</bean>
Now, with these 2 lines of code:
ApplicationContext ctx = new ClassPathXmlApplicationContext("app.xml");
Foo foo = ctx.getBean(Foo.class);
The foo object that was configured can be retrieved, and all its properties including bar will be set. This is the core use case of Spring, i.e. letting you configure how the building blocks of your application resolve their dependencies at runtime. Initially Spring was all about configuration outside of code, but the focus now has slightly changed, with things like component scans and Java configuration...
Anyway, to conclude with this brief example, the following line of code will print 10:
System.out.println(foo.getBar().getI());
In this example, I took Foo and Bar, but it could as well be a Web Service, a service implementing some business logic, a database, an ORM facade, a template engine, a thread pool, anything... But mostly components dealing with data objects, not data objects themselves, though this is entirely possible.
Now to return with your use case, in a Spring app, I would generally have these components if I'm coding a Web app with a database: a controller (the Web boundary), a service (for business logic), a repository (for querying) and of course a data source. I won't delve into too much details here (no declarative transactions for example). Notice that with this configuration, no specific data provider is compiled into my Java code, it remains in the configuration:
<bean id="cdController" class="demo.compactdisc.CdController">
<property name="cdService" ref="cdService" />
</bean>
<bean id="cdService" class="demo.compactdisc.CdServiceImpl">
<property name="cdRepository" ref="cdRepository" />
</bean>
<bean id="cdRepository" class="demo.compactdisc.CdRepositoryImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="test"/>
<property name="password" value="s3cr3t"/>
</bean>
With your domain, the repository would return the compact discs from the database to the service, the service to the controller and the controller to the user. Compact discs would not be described as Spring beans but would certainly be parameters and return values from the actual Spring beans.
You just need to have one Album class and annotate it as a #Component or do it via xml.
The terms bean and POJO are interchangeable. As per Spring in action 4rd edition, Spring tries hard to be a non-invasive framework.
(...)the classes in a Spring-based application often have no
indication that they’re being used by Spring. At worst, a class may be annotated with one of Spring’s annotations, but it’s otherwise a POJO
and
Although Spring uses the words bean and JavaBean liberally
when referring to application components, this doesn’t mean a Spring component
must follow the JavaBeans specification to the letter. A Spring component can be
any type of POJO.
The use case is that you can use the Spring Dependency Injection to wire your beans on run-time, your application can benefit from Spring in terms of simplicity, testability, and loose coupling.
In short, a Spring bean as you refer is just a POJO used in the context of an Spring Application. If you use the xml mapping instead of the annotation, your class will be just another regular Java class, a Plain Old Java Object.
If there are n albums in database, so should I create n album beans?
I would think not. If there are n albums it would be very cumbersome to include them all explicitly in your App.config file if that's what you're referring to; but you could. You would probably add an AlbumService (#Service) #Bean and associated #Repository to handle writing and retrieving them from the DB.
If it is not, how the n albums represented in application? Is it just
a POJO domain model (not a bean)?
You could have an Album #Entity bean with the attributes of an album. When you save an album you'd set the attributes as opposed to having individual components implementing a common interface. Your DB would have n albums in it. If you needed to retrieve just one Beatles album you could query based on the album title, for example. If you wanted them all you could do albumService.findAll(); and get a container of them.
What is the real use case using Spring Bean?
Spring is the real use case of a Spring Bean. According to the Spring IoC Container Reference:
In Spring, the objects that form the backbone of your application and
that are managed by the Spring IoC container are called beans. A bean
is an object that is instantiated, assembled, and otherwise managed by
a Spring IoC container. Otherwise, a bean is simply one of many
objects in your application. Beans, and the dependencies among them,
are reflected in the configuration metadata used by a container.
I can't provide a better answer than what's contained in the documentation or given in this answer.

Spring annotation component

I'm having some problems understanding how to use annotations, especially with beans.
I have one component
#Component
public class CommonJMSProducer
And I want to use it in another class and i thought I could do that to have a unique object
public class ArjelMessageSenderThread extends Thread {
#Inject
CommonJMSProducer commonJMSProducer;
but commonJMSProducer is null.
In my appContext.xml I have this :
<context:component-scan base-package="com.carnot.amm" />
Thanks
You have to configure Spring to use this autowiring feature:
<context:annotation-config/>
You can find the details of annotation-based config here.
ArjelMessageSenderThread also have to be managed by Spring otherwise it won't tamper with its members since it does not know about it.
OR
if you cannot make it a managed bean then you can do something like this:
ApplicationContext ctx = ...
ArjelMessageSenderThread someBeanNotCreatedBySpring = ...
ctx.getAutowireCapableBeanFactory().autowireBeanProperties(
someBeanNotCreatedBySpring,
AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT, true);
OR
as others pointed out you can use annotations to use dependency injection on objects which are not created by Spring with the #Configurable annotation.
It depends on how you create instances of ArjelMessageSenderThread.
If ArjelMessageSenderThread is a bean that should be created by spring you just have to add #Component (and make sure the package is picked up by the component scan).
However, since you extend Thread, I don't think this should be a standard Spring bean. If you create instances of ArjelMessageSenderThread yourself by using new you should add the #Configurable annotation to ArjelMessageSenderThread. With #Configurable dependencies will be injected even if the instance is not created by Spring. See the documentation of #Configurable for more details and make sure you enabled load time weaving.
I used XML instead of annotations. This seemed difficult for not a big thing. Currently, I just have this more in the xml
<bean id="jmsFactoryCoffre" class="org.apache.activemq.pool.PooledConnectionFactory"
destroy-method="stop">
<constructor-arg name="brokerURL" type="java.lang.String"
value="${brokerURL-coffre}" />
</bean>
<bean id="jmsTemplateCoffre" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref local="jmsFactoryCoffre" />
</property>
</bean>
<bean id="commonJMSProducer"
class="com.carnot.CommonJMSProducer">
<property name="jmsTemplate" ref="jmsTemplateCoffre" />
</bean>
And another class to get the bean
#Component
public class ApplicationContextUtils implements ApplicationContextAware {
Thanks anyway

Does spring mvc have the concept of before/after controller action events?

Does spring mvc have the concept of events firing before/after a controller action?
I am currently using a filter, but I could also inherit from a basecontroller for specific sections of my website and use before/after events if they exist.
So I mean I can create an event that fires just before a controller's action fires, or an event that fires after.
I think you are looking for interceptors. I don't know what strategy you are using for routing you requests to your controller methods, so I assume you are using annotations. Then, here is how you could put your interceptor on the stack:
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<ref bean="loginInterceptor"/>
</list>
</property>
</bean
Where loginInterceptor is the id of a bean declared in your application context which implements the interface org.springframework.validation.Validator
This looks like something you can achieve using Spring AOP.

Inject an external property into Spring context

I have three apps in a Spring 2.5 managed project that share some code and differ in details.
Each application has a property (java.lang.String) which is used before the application context is built.
Building the app context takes some time and cannot happen first. As such, it's defined in each individual application. This property is duplicated in the context definition since it is also needed there. Can I get rid of that duplication?
Is it possible to inject that property into my application context?
Have a look at PropertyPlaceholderConfigurer.
The Spring documentation talks about it here.
<bean id="myPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:my-property-file.properties"/>
<property name="placeholderPrefix" value="$myPrefix{"/>
</bean>
<bean id="myClassWhichUsesTheProperties" class="com.class.Name">
<property name="propertyName" value="$myPrefix{my.property.from.the.file}"/>
</bean>
You then have reference to that String to anywhere you'd like in your application context, constructor-arg, property etc.
With spring 3.0 you have the #Value("${property}"). It uses the defined PropertyPlaceholderConfigurer beans.
In spring 2.5 you can again use the PropertyPlaceholderConfigurer and then define a bean of type java.lang.String which you can then autowire:
<bean id="yourProperty" class="java.lang.String">
<constructor-arg value="${property}" />
</bean>
#Autowired
#Qualifier("yourProperty")
private String property;
If you don't want to deal with external properties,you could define some common bean
<bean id="parent" class="my.class.Name"/>
then initialize it somehow, and put into common spring xml file, lets say common.xml. After that, you can make this context as a parent for each or your apps - in your child context xml file:
<import resource="common.xml"/>
and then you can inject properties of your parent into the beans you're interested in:
<bean ...
<property name="myProperty" value="#{parent.commonProperty}"/>
...
</bean>

How to register handler interceptors with spring mvc 3.0?

It should be easy:
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<ref bean="myInterceptor" />
</list>
</property>
</bean>
but this way the interceptor isn't called.
By default, Spring will register a BeanNameUrlHandlerMapping, and a DefaultAnnotationHandlerMapping, without any explicit config required.
If you define your own HandlerMapping beans, then the default ones will not be registered, and you'll just get the explicitly declared ones.
So far, so good.
The problem comes when you add <mvc:annotation-driven/> to the mix. This also declares its own DefaultAnnotationHandlerMapping, which replaces the defaults. However, if you also declare your own one, then you end up with two. Since they are consulted in order of declaration, this usually means the one registered by <mvc:annotation-driven/> gets called first, and your own one gets ignored.
It would be better if the DefaultAnnotationHandlerMapping registered by <mvc:annotation-driven/> acted like the default one, i.e. if explicitly declared ones took precedence, but that's not the way they wrote it.
My current preference is to not use <mvc:annotation-driven/> at all, it's too confusing, and too unpredictable when mixed with other config options. It doesn't really do anything especially complex, it's not difficult or verbose to explicitly add the stuff that it does for you, and the end result is easier to follow.
Problem I faced: Spring MVC tag doesn't go well with custom definition of DefaultAnnotationHandlerMapping.
Why..? the reason is very well explained in the answers above.
Why i wanted to use DefaultAnnotationHandlerMapping? I want to define an interceptor for my every request. a Spring-Mobile interceptor to determine the USER AGENT..mobile or a browser?
Now Due to this clash of mvc-annotation and DefaultAnnotationHandlerMapping, I cant use DefaultAnnotationHandlerMapping anymore.
The problem comes down to how can i register my interceptors with tag.
The solution was simple...but hard to find. Posting it so it can be helpful to the other solution seekers..
Use tag and register the interceptor bean in your dispathcer-servlet.xml
example :
<mvc:interceptors>
<!-- This runs for all mappings -->
<bean class="main.com.XXX.MobileDeviceResolverHanlderInterceptor"/>
</mvc:interceptors>
The reason for this behaviour is that two beans of type org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping exist in the application context. Spring resolves the two, but asks only the first for interceptors. To fix this, the following init parameter should be set to the DispatcherServlet
<init-param>
<param-name>detectAllHandlerMappings</param-name>
<param-value>false</param-value>
</init-param>
This makes the dispatcher servlet use only the handlerMapping defined in the x-servlet.xml
It is beyond me why this is the default behaviour. I'm expecting an answer from the spring community.
In my case I can NOT get rid of <mvc:annotation-driven/> as I am using jackson for json support using annotation.
What I tried, moved my all interceptors <mvc:interceptors> in separate "xml" file (interceptor-config.xml) and imported it from my x-dispatcher-servlet.xml
<import resource="interceptor-config.xml"/>
It solve my issue and avoid default 'DefaultAnnotationHandlerMapping' beans my application context.
Rather than creating separate 'xml', you can copy/paste interceptor contents directly in 'x-dispatcher-servlet.xml'.
Following is my interceptor:
<mvc:interceptors>
<mvc:interceptor>
<!-- Intercepting specific URL -->
<mvc:mapping path="/abc/**" />
<bean id= "myInterceptor"
class="xx.xxx.xxx.MyInterceptor" />
</mvc:interceptor>
<mvc:interceptors>
In Spring MVC 3.0 you can use <mvc:interceptors> instead of manual defining the handler mapping.

Categories