Spring - autowired fields are null - java

I faced a problem with Spring Framework: #Autowired are null, but Spring doesn't throw any exceptions, and I can't understand, why are these fields null.
I have a class:
package com.processing.gates;
public class Main {
private final ApplicationContext context = Context.getContext();
#Autowired private PaymentGateFactory paymentGateFactory;
#Autowired private CalculatorChooser calculatorChooser;
//...
}
And for example I have the following class:
package com.processing.gates.comission;
#Component
public class CalculatorChooser {
//...
}
Here is my Spring configuration xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<context:annotation-config />
<context:component-scan base-package="com.processing.gates"/>
<bean id="logPath" class="java.lang.String"> <!-- путь к папке с логами -->
<constructor-arg value="/home/yoba/NetBeansProjects/processing/gates/log/"/>
</bean>
<!-- ... -->
</beans>
When I try to write in xml:
<bean id="calculator" class="com.processing.gates.comission.CalculatorChooser"/>
and get it from code:
CalculatorChooser cc = (CalculatorChooser)Context.getContext().getBean("calculator");
it works fine. But #Autowired doesn't work. How can I fix this? Thanks!

Let Spring manage the bean by either declaring a Main bean in the application context file or by using the #Component annotation as you've already done for CalculatorChooser
<bean id="mainBean" class="com.processing.gates.Main"/>

Related

could not autowire spring

I am trying to learn spring MVC and created a rest service but I am getting bean autowiring problem.
Could not autowire field: taxApp.dao.daoImpl.userDaoImpl taxApp.controller.loginController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [taxApp.dao.daoImpl.userDaoImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency
The structure of my spring project looks like
src
main
java
taxApp
controller
loginController.java
model
user.java
dao
daoImpl
userDaoImpl.java
userDAO.java
resources
database
data-source-cfg.xml
user
spring-user.xml
spring-module.xml
webapp
web-inf
dispatcher-servlet.xml
web.xml
index.jsp
Following is how the files looks like
dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="taxApp" />
<context:annotation-config />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
spring-user.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="userDAO" class="dao.impl.userDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
spring-module.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Using Oracle datasource -->
<import resource="database/data-source-cfg.xml" />
<import resource="dao/spring-user.xml" />
</beans>
All the other implementation like controller, DAO, service and model look like
loginController.java
#RestController
public class loginController {
#Autowired
userDaoImpl userService; //Service which will do all data retrieval/manipulation work
//other methods
}
userDAO.java
public interface userDAO {
public void insert(user _user);
public user findUserByEmail(String email);
}
userDaoImpl.java
public class userDaoImpl implements userDAO{
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
//other methods
}
Mark your daoimpl as
#repository
public class userDaoImpl implements userDAO{}
Autowire interface rather marking an concrete class.
Go with java config for spring application much easier to understand.
Could you change the following:
#RestController
public class loginController {
#Autowired
userDaoImpl userService; //Service which will do all data retrieval/manipulation work
//other methods
}
by the following:
#RestController
public class loginController {
#Autowired
#Qualifier("userDAO")
userDaoImpl userService; //Service which will do all data retrieval/manipulation work
//other methods
}
and see the result?
u r having one setter injection in the bean u want to autowire u have to do something like this
//Autowired annotation on variable/setters is equivalent to autowire="byType"
#Autowired
private Employee employee;
#Autowired
public void setEmployee(Employee emp){
this.employee=emp;
}

Why is autowired properties file null?

I autowired some beans from my testConfig.xml, and it works fine but when I want to autowire a properties file it gives null, the properties file is near of my xml in selenium folder. My testConfig.xml looks like this :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd" >
<bean id="base" class="java.net.URI">
<constructor-arg value="http://localhost:8080/MySite" />
</bean>
<bean id="siteBase" class="java.net.URI">
<constructor-arg value="http://localhost:8080/MySite/site" />
</bean>
<bean id="adminBase" class="java.net.URI">
<constructor-arg value="http://localhost:8080/MySite/admin" />
</bean>
<bean id="firefoxDriver" class="org.openqa.selenium.firefox.FirefoxDriver" destroy-method="quit"/>
<context:annotation-config/>
<util:properties id="seleniumSelectors" location="classpath:selenium/selenium-selectors.properties"/>
</beans>
and here I want to autowire it:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "/testConfig.xml" })
public abstract class AbstractUITest extends TestCase{
#Autowired
protected URI base;
#Autowired
protected URI siteBase;
#Autowired
protected URI adminBase;
#Autowired
protected WebDriver firefoxDriver;
#Autowired
#Qualifier("seleniumSelectors")
protected Properties selectors;
protected By getBySelectorKey(String key){
if(key.endsWith(".xpath")){
return By.xpath(selenium.getProperty(key));
}
}
Just the selectors object is null and I don`t know why, any suggest?
UPDATE 2:
I made a mistake everithing is null when the selector is null.I cheked Initialization in my test runs before autowired, somehow this
public class AdminCandidatesPageUITest extends AbstractAdminUITest {
private By COMPONENT_QUERY_TEXTBOX_EMAIL = getBySelectorKey("admin.candidates.edit.textbox.email.xpath");
private By COMPONENT_QUERY_TEXTBOX_EMAIL_ERROR = getBySelectorKey("admin.candidates.edit.textbox.email.errors.xpath");
should run after seleniumSelector is autowired. Any suggest?
Try to move tag <context:annotation-config/> one line down. I am not sure but it seems that wiring triggered by this tag happens before creating of seleniumSelectors, so it is still null at the moment.
BTW if you mark your properties as #Required the context will fail to start and throw exception because one of the properties is not wired. This is probably preferable than failing later at runtime.

Spring #Autowired comes as null

I have #Component, A, which AutoWires a class which contains simple configurations for class A. I've created a bin for configuration file. But for some reason it comes as null. Could you please help me to find out the problem?
#Component
public class SearchEngineDriver {
#Autowired(required = true)
private EngineContext context;
public SearchEngineDriver(){
String clusterName = context.getClusterName();
}
}
public class EngineContext {
private String clusterName;
public EngineContext(String clusterName){
this.clusterName = clusterName;
}
public String getClusterName(){
return this.clusterName;
}
}
3rd class.
#Autowired
private SearchEngineDriver searchEngineDriver;
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="org.electronsoftware" />
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/" />
<import resource="classpath*:/application-context.xml"/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:property-placeholder location="classpath:application.properties"/>
<bean id="searchEngineContext" class="org.electronsoftware.KGB.search.context.EngineContext" >
<constructor-arg value="${kgb.search.engine.clustername}"/>
</bean>
</beans>
You are accessing the autowired field from the constructor. At the time the constructor runs, Spring has not yet got the chance to initialize the field. Instead use a #PostConstruct method to perform logic which depends on the autowired value.

Spring #Value annotation and setter injection difference

When I am setting a value using #Value annotation from a property file, its not working, whereas setting using setter injection works.
my properties file like this.
app.work.dir=file:${user.home}/WORK
class file like below.
#Value("#{configProperties['app.work.dir']}")
private String workdir;
and this is my xml setting.
<util:properties id="configProperties" location="classpath:config.properties" />
when use setter injection like below then it works fine.
<bean id="sampleService" class="aaa.SampleService">
<property name="workdir" value="${app.work.dir}" />
</bean>
I'm not sure why and if possible i want to use #Value annotation.
please refer to junit test case below.
xml configulation:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:property-placeholder location="classpath:testconfig.properties" />
<util:properties id="sampleProperties" location="classpath:testconfig.properties" />
<bean id="exampleA" class="aa.sample.SampleA" />
<bean id="sampleB" class="aa.sample.SampleB" >
<property name="workdir" value="${work.dir}" />
<property name="tempdir" value="${work.dir.test}" />
<property name="aaa" value="${aaa}" />
</bean>
</beans>
sample service class:
package aa.sample;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
#Service
public class SampleA {
#Value("#{sampleProperties['work.dir']}")
private String workdir;
#Value("#{sampleProperties['work.dir.test']}")
private String tempdir;
#Value("#{sampleProperties['aaa']}")
private String aaa;
//getter setter deleted
}
properties file:
work.dir=file:${user.home}/WORK
work.dir.test=${work.dir}/TEST
aaa=bbb
and junit test class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration({ "/testcontext.xml" })
public class ExampleTest {
#Inject
private SampleA sampleA;
#Inject
private SampleB sampleB;
#Test
public void testValueAnnotation() {
assertThat(sampleA.getAaa(), is("bbb"));//ok
String tempdir = sampleA.getTempdir();
String workdir = sampleA.getWorkdir();
assertFalse("[sampleA] temp dir should not have ${work.dir}", tempdir.indexOf("${work.dir}") >= 0);//ng
assertFalse("[sampleA] workdir dir should not have ${user.home}", workdir.indexOf("${user.home}") >= 0);//ng
}
}
The bean generated by
<util:properties id="sampleProperties" location="classpath:spring.properties" />
basically translates to a map. This notation
#Value("#{sampleProperties['work.dir']}")
requests one of its valued mapped with the key work.dir. There's no property resolution that occurs on the value returned. It's taken literally.
This, on the other hand,
<property name="tempdir" value="${work.dir.test}" />
requests a property, called work.dir.test which can be recursively resolved.

spring autowiring not working

Hi,
I am using spring 3.0 with Quartz in a scheduler class. I have created the application context by
private static final ClassPathXmlApplicationContext applicationContext;
static {
applicationContext = new
ClassPathXmlApplicationContext("config/applicationContext.xml");
}
The problem is that none of the #Autowired beans actually get auto-wired, so I have to manually set dependencies like this:
<bean class="com.spr.service.RegistrationServiceImpl" id="registrationService">
<property name="userService" ref="userService" />
</bean>
Example of where I'm using #Autowired:
public class RegistrationService {
#AutoWired private UserService userService;
// setter for userService;
}
public class UserService{
// methods
}
I also made sure to enable the annotation configuration in my Spring config:
<context:annotation-config/>
<bean id="registrationSevice" class="RegistrationService"/>
<bean id="userService" class="UserService"/>
Why is #Autowired not working for me?
You haven't provided the UserService class source code so I can't be sure about your problem. Looks like the UserService class is missing a 'stereotype' annotation like #Component or #Service. You also have to configure the Spring classpath scanning using the following configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Add your classes base package here -->
<context:component-scan base-package="your.package"/>
</beans>
Your beans must include one of the Spring stereotype annotations like:
package your.package;
#Service
public class UserService{
}
Atlast i got it resolved by adding the
<context:component-scan base-package="your.package"/>
in my applicationContext.xml. Thank u all for your support.

Categories