Spring Bean and Autowire to datasource - spring

Noob to Spring. I have 2 files:
foo-servlet.xml which has the following statement:
<bean id:"DAO" class="a.b.data.MyDAO"/>
fooController.java has the following:
#Controller
public class FooController{
#Autowired
private FooDAO fooDAO;
public void setFooDAO (FooDAO fooDAO){ this.fooDAO = fooDAO;}
My question: Is Spring actually replacing / injecting the definition of DAO in the servlet into my FooDAO? I'm trying to understand the 'tie-in' between the bean and how Spring know to substitute that file for my FooDAO in the controller.
Oh, and there is no mention of #Repository or #Component anywhere in this example code...

The XML looks kind of corrupted. I think it needs to be id=DAO
As far as i know: Autowiring is either done via the type or the name and the type.
So when MyDAO implements FooDao your bean will be considered for Autowiring.
But this is just a guess. The code of the Daos and the rest of the configuration would be helpful to give a correct answer to this question.
Understanding Spring #Autowired usage
This might answer your question as well.

Related

How do I autowire an instance of a java class?

I have a class that starts like this:
import javax.mail.Session;
//... more imports
#Component("eMailUtility")
public class MailUtility {
#Autowired
Session mailSession;
//...
}
My IDE tells me "Could not autowire. No beans of 'Session' type found."
This message doesn't surprise me, but I'm not sure how to fix it. Session is a final class with factory methods but no public constructors. I can easily instantiate a Session somewhere, but I don't know what I need to do to make it recognizable as a target of an autowired injection. All the examples I've found on the internet show how to autowire an instance of a class that I wrote, which doesn't help me here.
(A detailed explanation of exactly how autowire works, which doesn't gloss over anything, would be very helpful, but I can't seem to find one. If you know of a good link, that would be helpful.)
You'd have to create a method in a class that is annotated with #Configuration that returns a Session object and annotate that method with #Bean. In your case something like this:
#Bean
public Session session() {
return <instance>;
}
If it was one of your own classes you could also annotate it with #Component, or other annotations that are itself annotated with #Component. Spring would then find the class with this annotation and automatically create the bean for you.
For an explanation about #Autowired you can look at this answer: Understanding Spring #Autowired usage

How to inject Spring's Validator implementation?

I started with generating my application using JHipster v.3.5.1.
After some time, I needed to create validator to perform some business logic validation on my entity, when it is created with POST. So I made:
#Component
public class MyValidator implements Validator
Then, I tried to inject it into my controller (annotated with #RestController), but no matter which way I tried, it always resulted in something like that:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.my.app.service.domain.MyValidator] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
Ways I tried to create bean and inject it
#Autowired
private MyValidator myValidator;
#Inject
private MyValidator myValidator;
#Autowired
#Qualifier("myValidator")
private MyValidator myValidator; (with #Component("myValidator") on class)
#Inject
#Qualifier("myValidator")
private MyValidator myValidator; (with #Component("myValidator") on class)
//Below was inserted in class annotated with #Configuration
#Bean
public MyValidator myValidator() {
return new MyValidator();
}
However I tried it - it failed. I always got NoSuchBeanDefinitionException or field value was set to null.
I've also checked class location in project structure. To be 100% percent sure it's well placed, I've put it in package the with #Services, which are scanned and work well. No effect.
I know that it seems to be pretty easy task and I know this injection is possible (I've seen it done in project in my work), but somehow I'm not able to make it work in my project.
Maybe I'm missing something in configuration? Thanks for any help :)
I believe your issue is that when you use #Autowired inside a class annotated with #Configuration you are just referencing to a bean that is defined in a separate configuration file, that is it has to be declared in another file also with the #Configuration annotation.
If you want to refer refer to another implicit bean such as your validator annotated with #Component you will need to do it in another implicit bean also annotated to with implicit notation such as #Component, #Service, #Controller, etc
The #Autowired alone should work unless you have more than one class implementing the same interface. That is when you will need to use the #Qualifier.

Is it possible to retrieve a Spring bean with prototype scope without using ApplicationContextAware

Using Spring 3.1. If I want to retrieve a bean with prototype scope (i.e. I want a different instance of the class each time), is it possible to retrieve the bean without having to use an ApplicationContextaware class?
This is how I do it at present
#Component
#Qualifier("MyService")
public class MyServiceImpl implements MyService {
#Override
public void doSomething() {
Blah blah = (Blah)ApplicationContextProvider.getContext().getBean("blah");
blah.setThing("thing");
blah.doSomething();
}
}
#Component("blah")
#Scope("prototype")
public class Blah {
....
}
where ApplicationContextProvider implements ApplicationContextAware.
Is it possible to do this with annotations or simple Spring configuration without having to use an ApplicationContextAware class?
Spring has some fairly sophosticated methods for achieving what you're after...
See the spring documentation: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-factory-scopes-other-injection
Searching for spring proxy scope on google also threw up some results...
You don't really need a ApplicationContextAware. You just need a BeanFactory (ApplicationContextAware is just a convinient way to get it).
A bean with scope prototype just means that everytime ApplicationContext.getBean is called a new instance of the bean is created. If you try to inject a prototype bean in a singleton, your prototype bean will be injected once (and so is no more a prototype).
There is something called method injection that may help you if you really need it, but it is more complex than simply calling applicationContext.getBean().

Injecting a bean to use in Controllers throughout the application

I'm using spring mvc 3.1.x and jets3t.
I have a DataAccessObject that i instantiate as a Singleton bean..
I managed to get it working through extending the applicationcontextloader class and adding it to the web.xml
EDIT:
I changed my method, I tried inject and autowired but it's not suitable for my needs.
What I've done was to implement ApplicationContextAware and set it up as a bean, in the code I use it as follows:
ApplicationContext ctx = BannerApplicationContext.getApplicationContext();
BannerGenericDAO bdao = (BannerGenericDAO) ctx.getBean("dao");
I'm new to Spring and in general the servlet world..
Questions are:
what's the best way of doing this? Is this considered a "best-practice"?
How do you inject an object, keeping other method fields that are not supplied by autowiring?
How do you get an object to be used throughout the entire application?
Thanks!!
You could use annotations in your controller.
#Controller
public class MyController{
#Autowired // or #Inject, which is more JEEish (JSR330).
private SomeDao daoService;
}
Given "SomeDao" is the type of your singleton DAO, of course.

#Autowired annotations behavior in Spring 3

I wanted to understand how exactly the #Autowired annotation works.
import com.test.WorkFlowDAO;
public class ServiceCentralBOImpl implements IServiceCentralBO
{
/**
* Logger for logging functionality.
*/
private static final Log log = LogFactory.getLog(ServiceCentralBOImpl.class);
#Autowired
private WorkFlowDAO workFlowDAO;
.
.
.
}
and the bean is declared in my Spring applicationContext.xml file:
<bean id="workflowDAO" class="com.test.WorkFlowDAO">
</bean>
Upon closer inspection you can see the two IDs in the Java class and the context XML file are different.
workFlowDAO and
workflowDAO
[The letter 'f' is different in the two IDs]
Since my application runs just fine even with this configuration; I wanted to know,
how does #Autowired annotation work so that it does not complain when the bean IDs do not match exactly.
In case of simple bean usage; Spring would have complained of mismatching bean names.
I am running a J2EE application with Spring 3.0.5 on Websphere App Server 7.0
Let me know if any more information is required.
#Autowired matches the beans by type. The ID is not considered.
If you declare another bean of the same type in your XML configuration, Spring would complain about not being able to determine the correct bean.
If you want to use IDs together with #Autowired you can do so by utilizing #Qualifier although #Resource is recommended in this case.
Find some more info on that topic here.
Completely agree with the first comment.
If you want your beans to be autowired by name, you may consider using #Qualifier("givenName").
See for all details:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html

Resources