#Autowired in bean not in spring context - spring

I am new to springs. Is there an alternative for autowired to be used in a ordinary java bean which is not present in spring context.

You can do so by using Spring #Configurable with some AspectJ magic.
If you need a detailed explanation, here is the link.
And here is a brief overview of how it can be achieved.
First you have some bean that you want injected somewhere:
#Component
public class InjectedClass {
// ...
}
Then, you have a class that is not spring-container managed, that you want to instantiate. You want autowiring to work with this class. You mark it as a #Configurable.
#Configurable
public class NonContainerManagedClass {
#Autowired
private InjectedClass injected;
// ...
}
Now you need to tell spring that you want this non-container managed autowiring to work. So you put the following in your spring configuration.
<context:load-time-weaver />
<context:spring-configured />
Now, since this kind of thing requires modification of the bytecodes of your #Configurable class. So you tell Tomcat to use a different classloader. You can do so by creating a context.xml in your application's META-INF diretory and putting the following in there.
<Context path="/youWebAppName">
<Loader loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader"
useSystemClassLoaderAsParent="false"/>
</Context>
Now, Tomcat needs to find that classloader. You can ensure that by putting Spring's spring-tomcat-weaver.jar (probably named org.springframework.instrument.tomcat-<version>.jar) in your tomcat installation's lib directory, and voila, the aspectj magic starts working. For classes that are annotated with #Configurable annotation, the #Autowired dependencies are resolved automatically; even if the instances are created outside of the spring-container.
This is probably the only way to make that work with Spring, in a clean manner. Make sure that you have appropriate dependencies in your classpath.
Another way would be to use the full AspectJ functionality and providing custom aspects around all your constructors and handling the dependency-injection yourself.

Related

Injected bean reset to NULL in the Aspect

I am new Spring AOP and Aspectj. I have seen various posts related to injected bean in an aspect being null and I have run into a similar problem. I am still not clear how I should proceed to get past the problem I am currently encountering.
Issue: Currently we are using Spring 3.2.3 and all injection is through Annotation. In my case, the dependent bean is injected properly by Spring but at the point of execution the injected bean is NULL. BTW, this doesn't happen all the time but what I can say is the stack trace when it fails and when it succeeds is slightly different. When the injected bean is not null (I can successfully use the injected bean service), the call to the before advice (in the aspect) always happens before the target method is called as it should.When the injected bean is NULL, the call to the aspect is from the first statement of the target method. At this point, I think another aspect is instantiated and has no reference to the injected bean. Here is the aspect I have created:
#Component
#Aspect
public class Enable{
private NameService nameService;
#Autowired
public void SetNameService(NameSerice service){
// service is injected properly
this.nameSerice = service;
}
#Before("* *.*(..)")
public void callBefore(JoinPoint jp){
//sometimes nameService is null and sometimes it not not
this.nameService.lookup(...);
}
}
Examining the various posts, one way to get around this (as suggested in the post) is to configure the aspect in the XML configuration file and use the factory-method ="aspectOf" and in the configuration inject the reference to the NameService bean as a property. Our whole project uses Annotation based injection (as stated earlier). Assuming I can still configure the above aspect in an XML configuration file, how can I get the reference NameService bean Id so that I can add it to the configuration. I also saw a post related to using Configurable annotation but I assume that is for objects created outside the Spring IOC.
Currently, the aspects are woven using Aspectj compile option in pom.xml. Our root-context.xml contains the entry context:annotation-config and the aspect is injected into Spring IOC because component-scan is turned on for the folder where the aspect resides. Any help will be appreciated
This is well common error when use aspects in spring, you should add
<context:spring-configured/>
and
<aop:aspectj-autoproxy />
also add
#Configurable
#Aspect
public class Enable
To your appContext.xml
aspectOf is another style to do the above but I prefer use the nature of context.
It might be too late to answer this question. But i have come across the same situation and i fixed it as below.
1) Have a setter and getter for "NameService" in your aspect class.
2) Mark "NameService" with #Component ("nameService")
3) Configure "nameService" in xml configuration using setter injection.
4) Re-Start your server after making changes.
This should resolve the problem of getting null for "NameService" in aspect.

Spring-data-mongo: MongoRepository not being wired unless I add #Component annotation

I am having a little weird behavior with my spring-data-mongo where my repository package is not being scanned by the <mongo:repositories/> tag. I am using spring 3.2.3.RELEASE with spring-data-mongo 1.2.1.RELEASE.
I have a project called edowmis and in it there are 2 maven modules, datalayer and web which a webapp.I am using the datalayer in isolation so the other module can be ignored. I have an application context for datalayer
So I wanted to test my setup by writing a small Unit/Integration test but I've noticed I can't autowire my UserRepository because It says there isn't such a bean
Since I am using IntelliJ I can see certain visuals when things are ok and not ok. I've addec <context:component-scan/> to my application context but no result.
But when I add the #Component annotation it has started identifying the Class.
all information you might need is on pastie.org
Is the #component or #Repository really necessary or something is wrong with my configuration?
Yes, the #Component or #Repository is necessary. The scan simply indicates that spring should look for classes identified via annotations (#Component, #Repository, #Service) and load them as beans. If you don't use repository or component scan, you would have to manually instantiate all spring-managed beans via XML configuration or Java configuration.
You have to tell spring which classes to turn into beans as it doesn't assume everything in the classpath is supposed to be a spring-managed bean, which is why you need to use the annotations.

How to inject service in JSF managed bean without using Spring IOC

Typically if I have to inject a service in Spring I use
<bean id="mycontroller" class="com.MyController">
<property name="myService" ref="myService" />
and
<bean id="myService" class="com.MyService"></bean>
How to do the same when using JSF? I dont want to use two IOC containers for the beans and rather keep it in faces context itself. I have seen links such as
JSF 2 inject Spring bean/service with #ManagedProperty and no xml
and A problem about injecting spring bean into jsf bean . They talk about injecting Spring managed bean into JSF context.
What I am trying to do must be really simple but am not able to find any relevant info. Am a newbie and will appreciate any help.
I think you may be confused by the word "bean".
The thing is, the "service" you are talking about is also a Spring bean, right?
You probably have it as a service cause it has some additional features (probably transaction management) added by Spring, according to your configuration.
The JSF IoC container is very simplistic, it does not allow you to configure its lifecycle to include transaction management, AOP and things like that. Those things you have to do with Spring (or EJB, in a Java EE environment).
So, when using JSF with Spring, you usually have two choices:
Either you put the backing beans for the JSF pages in the JSF container, annotating them with #ManagedBean, #RequestScoped, #ViewScoped, etc; and injecting any necessary Spring bean with #ManagedProperty in a property (a setter is required)
Or skip the JSF container and put the backing beans along with all others in the Spring container, and use the Spring scopes of request/session, annotating them with Spring's annotations #Component, #Scope("request"), #Scope("session") and injecting with #Autowired, #Qualifier and the like.
Personally, faced with that choice I'd go with the first choice, cause it gives you #ViewScoped and some other niceties. It's true it makes use of two IoC containers but then, which Java EE app does not?
If you want to go the second route anyway, you may also add a view scope for Spring beans, backed by JSF viewMap.
What Spring calls a "Service" is in Java EE terms an "EJB". EJB is out the box available in Java EE web profile containers like Glassfish, JBossAS and TomEE.
To create a stateless EJB service, just use #Stateless on the class:
#Stateless
public class SomeService {
public void doSomething() {
// ...
}
}
And to inject it in a JSF managed bean, just use #EJB on the property-to-be-injected:
#ManagedBean
#ViewScoped
public class SomeController {
#EJB
private SomeService service;
}
That's it. No getter/setter necessary. No XML boilerplate necessary.

Spring custom annotation - how to make it part of a library?

I've created a custom annotation (in Spring 3.05) that works great. I'd like to take that code and make it part of a library, packaged in a jar file, so I don't have to include my custom annotation code in each web app I write.
I'm unable to get Spring to act on the annotation, however. My library jar is in my web app's classpath and I tried scanning for it in applicationContext.xml:
<context:component-scan base-package="my.annotation.pkg" />
The field annotated with my custom annotation continues to be null.
Ideally I'd like to this to just work with a minimum of fuss and configuration, but so far I haven't had any success.
What part of Spring's wiring am I missing to get my custom annotation recognized when it's part of an external library?
Update
Here is how I "solved" it...just had to read a little more closely. In each context file (i.e. applicationContext.xml, dispatch-servlet.xml) I added the line:
<bean class="my.annotation.CustomInjector" />
...where my CustomInjector implements BeanPostProcessor. I based this on the code at this blog post: Implementing Seam style #Logger injection with Spring.
The author says I needed to do exactly what I did, so bad on me for not reading thoroughly. Why, though, is adding that bean definition required? Maybe Spring annotations are configured similarly under the hood - I just don't get why having the jar file on the classpath isn't enough.
Is your custom annotation annotated with the #Component annotation? From the Spring reference manual:
By default, classes annotated with #Component, #Repository, #Service, #Controller, or a custom annotation that itself is annotated with #Component are the only detected candidate components.
Alternatively, you could add a custom include-filter to the component-scan element in your XML configuration.

Is it possible to autowire dependencies that are created outside of an ApplicationContext?

I've got an application which uses JAXRS to map Restlet resources using annotations. However, the only entry point I have is essentially defining a list of resource classes in the application configuration. These classes are instantiated by Restlet or JAXRS, so I have no way to put them in my ApplicationContext. Is there a way to have Spring scan the classpath and autowire new instances as necessary? I've already tried using something like below:
#Autowired
private SessionFactory sessionFactory;
Unfortunately, it doesn't really work. Is there a way to do what I'm talking about here?
You can use AspectJ to dependency inject your beans that are created out of your control, or if you create objects using new. You can read more on Springs documentation: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-using-aspectj
Essentially what you will do is add #Configurable annotation to the class that you want to be target of injection. You also have to enable it in Spring by having in your Spring xml. Lastly you have to decide between compile time weaving or runtime weaving. Again you can get help from spring documentation.
Loadtime weaving: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-aj-ltw
If you use maven you can check this Stackoverflow question for setting up compile time AspectJ: Why doesn't AspectJ compile-time weaving of Spring's #Configurable work?
ApplicationContext.getAutowireCapableBeanFactory().autowireBean(object) will inject all dependencies into the object.

Resources