currently I have a spring project with an applicationContext.xml that defines some beans that are being used for code injection:
<bean class="com.example.Example1ClientImpl">
<constructor-arg type="java.lang.String" value="${EXAMPLE1_URL}" />
</bean>
<bean class="com.example.Example2ClientImpl">
<constructor-arg type="java.lang.String" value="${EXAMPLE2_URL}" />
</bean>
I want to refactor this code into another project that does not use spring. It runs on a JBoss server, so I assume these beans can be declared in ejb-jar.xml or jboss-ejb3.xml, but I can't figure out how.
Is it possible to do this and can somebody give me some pointers on how to do this?
EDIT: The ExampleXClientImpl classes are not defined in the project itself, they are defined in a dependency of the project. I could adapt this dependency, but I'd prefer if that's not necessary.
If your aim is to make EJB's out of those beans then I would try doing a mix of xml and annotations:
ejb-jar.xml
Here you define your environment properties:
<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee" version="3.0" metadata-complete="false">
<enterprise-beans>
<session>
<ejb-name>Configuration</ejb-name>
<env-entry>
<env-entry-name>EXAMPLE1_URL</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>url1</env-entry-value>
</env-entry>
<env-entry>
<env-entry-name>EXAMPLE2_URL</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>url2</env-entry-value>
</env-entry>
</session>
</enterprise-beans>
</ejb-jar>
Ejb
Here you create a Singleton (as this is the default Spring scope). IF you want to have the bean to have the default prototype scope of EJB's then you can annotate it with Stateless instead:
import javax.annotation.Resource;
import javax.ejb.Singleton;
#Singleton
public class Example1ClientImpl{
#Resource(name = "EXAMPLE1_URL")
private String url;
...
}
#Singleton
public class Example2ClientImpl{
#Resource(name = "EXAMPLE2_URL")
private String url;
...
}
I decided to use #Produces, I forgot that this existed. The solution looks something like this:
public class ClientProducer {
private static final String CLIENT1_ENDPOINT_VAR = "CLIENT1_URL";
private static final String CLIENT2_ENDPOINT_VAR = "CLIENT2_URL";
#Produces
public Example1Client produceExample1Client() {
String uri = System.getProperty(CLIENT1_ENDPOINT_VAR);
return new Example1ClientImpl(uri);
}
#Produces
public Example2Client produceExample2Client() {
String uri = System.getProperty(CLIENT2_ENDPOINT_VAR);
return new Example2ClientImpl(uri);
}
}
Related
In my Spring Integration webapp configuration I've added a property placeholder:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:ctx="http://www.springframework.org/schema/context"
...
xsi:schemaLocation="http://www.springframework.org/schema/context
...
">
<ctx:component-scan ... />
<ctx:annotation-config />
<mvc:annotation-driven />
<ctx:property-placeholder location="classpath:config.properties" trim-values="true" />
This is that file content:
apiPath=/requests
I'm sure this configuration works because I've tried using that value in a http inbound-channel-adapter:
<int-http:inbound-channel-adapter id="/api${apiPath}"
channel="httpRequestsChannel"
path="${apiPath}"
...>
</int-http:inbound-channel-adapter>
and if I change the property value the frontend application cannot reach the endpoint.
However, further in the context I have an endpoint so configured:
<int:header-value-router input-channel="httpRequestsChannel" ... >
<int:mapping value="POST" channel="httpRequestsPostChannel" />
...
</int:header-value-router>
<int:channel id="httpRequestsPostChannel" />
<int:chain input-channel="httpRequestsPostChannel">
<int:transformer method="transform">
<bean class="transformers.RequestToMessageFile" />
</int:transformer>
...
where I want to read the property value:
public class RequestToMessageFile {
#Autowired
private Environment env;
// ...
public Message<?> transform(LinkedMultiValueMap<String, Object> multipartRequest) {
System.out.println("Value: " + env.getProperty("apiPath"));
But on the console I see:
Value: null
I supposed once declared the property source in the XML that would be part of the whole web app environment, what am I missing? Should I declare the source in another place?
I noticed that if I add the following annotations:
#Configuration
#PropertySource("classpath:config.properties")
public class RequestToMessageFile {
the property is correctly found so I guess this is just a configuration problem.
In case it matters, here's the web.xml portion that configures integration:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/META-INF/spring.integration/context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
UPDATE
Partly following this answer I removed <ctx:property-placeholder> from the XML file and I added the following bean:
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
#Configuration
#PropertySource("classpath:config.properties")
public class WebappConfig {
}
And now both beans and the XML file can see the properties.
Quoting Martin Deinum:
No it isn't a configuration issue that is how it is supposed to work. The doesn't add properties to the environment. Where as the #PropertySource does.
Therefore you should remove <ctx:property-placeholder> from your XML configuration. Continue to use #PropertySource("classpath:config.properties") and also add this bean definition:
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
Pay attention how it has to be static do not load eagerly all other beans in the same #Configuration.
I've started my project by creating entities, services and JUnit tests for services using Spring and Hibernate. All of this works great.
Then I've added spring-mvc to make this web application using many different step-by-step tutorials, but when I'm trying to make Controller with #Autowired annotation, I'm getting errors from Glassfish during deployment. I guess that for some reason Spring doesn't see my services, but after many attempts I still can't handle it.
Tests for services with
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:/beans.xml"})
and
#Autowired
MailManager mailManager;
works properly.
Controllers without #Autowired too, I can open my project in web browser without trouble.
/src/main/resources/beans.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd">
<context:property-placeholder location="jdbc.properties" />
<context:component-scan base-package="pl.com.radzikowski.webmail">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!--<context:component-scan base-package="pl.com.radzikowski.webmail.service" />-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- Persistance Unit Manager for persistance options managing -->
<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="defaultDataSource" ref="dataSource"/>
</bean>
<!-- Entity Manager Factory for creating/updating DB schema based on persistence files and entity classes -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager"/>
<property name="persistenceUnitName" value="WebMailPU"/>
</bean>
<!-- Hibernate Session Factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--<property name="schemaUpdate" value="true" />-->
<property name="packagesToScan" value="pl.com.radzikowski.webmail.domain" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<!-- Hibernate Transaction Manager -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
/webapp/WEB-INF/web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="WebApp_ID" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring Web MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
/webapp/WEB-INF/mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-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="pl.com.radzikowski.webmail" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
pl.com.radzikowski.webmail.service.AbstractManager
package pl.com.radzikowski.webmail.service;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Master Manager class providing basic fields for services.
* #author Maciej Radzikowski <maciej#radzikowski.com.pl>
*/
public class AbstractManager {
#Autowired
protected SessionFactory sessionFactory;
protected final Logger logger = Logger.getLogger(this.getClass());
}
pl.com.radzikowski.webmail.service.MailManager
package pl.com.radzikowski.webmail.service;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
#Component
#Transactional
public class MailManager extends AbstractManager {
// some methods...
}
pl.com.radzikowski.webmail.HomeController
package pl.com.radzikowski.webmail.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import pl.com.radzikowski.webmail.service.MailManager;
#Controller
#RequestMapping("/")
public class HomeController {
#Autowired
public MailManager mailManager;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String homepage(ModelMap model) {
return "homepage";
}
}
Error:
SEVERE: Exception while loading the app
SEVERE: Undeployment failed for context /WebMail
SEVERE: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public pl.com.radzikowski.webmail.service.MailManager pl.com.radzikowski.webmail.controller.HomeController.mailManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [pl.com.radzikowski.webmail.service.MailManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Sorry for a lot of code, but I don't know what can cause that error anymore.
Added
I've created the interface:
#Component
public interface IMailManager {
added implements:
#Component
#Transactional
public class MailManager extends AbstractManager implements IMailManager {
and changed autowired:
#Autowired
public IMailManager mailManager;
But it still throws errors (also when I've tried with #Qualifier)
..Could not autowire field: public
pl.com.radzikowski.webmail.service.IMailManager
pl.com.radzikowski.webmail.controller.HomeController.mailManager...
I've tried with different combinations of #Component and #Transactional too.
Shouldn't I include beans.xml in web.xml somehow?
You should autowire interface AbstractManager instead of class MailManager. If you have different implemetations of AbstractManager you can write #Component("mailService") and then #Autowired #Qualifier("mailService") combination to autowire specific class.
This is due to the fact that Spring creates and uses proxy objects based on the interfaces.
I had this happen because my tests were not in the same package as my components. (I had renamed my component package, but not my test package.) And I was using #ComponentScan in my test #Configuration class, so my tests weren't finding the components on which they relied.
So, double check that if you get this error.
The thing is that both the application context and the web application context are registered in the WebApplicationContext during server startup. When you run the test you must explicitly tell which contexts to load.
Try this:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:/beans.xml", "/mvc-dispatcher-servlet.xml"})
I was facing the same issue while auto-wiring the class from one of my jar file.
I fixed the issue by using #Lazy annotation:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
#Autowired
#Lazy
private IGalaxyCommand iGalaxyCommand;
This may help you:
I have the same exception in my project. After searching while I found that I am missing the #Service annotation to the class where I am implementing the interface which I want to #Autowired.
In your code you can add the #Service annotation to MailManager class.
#Transactional
#Service
public class MailManager extends AbstractManager implements IMailManager {
Spent much of my time with this! My bad! Later found that the class on which I declared the annotation Service or Component was of type abstract. Had enabled debug logs on Springframework but no hint was received. Please check if the class if of abstract type. If then, the basic rule applied, can't instantiate an abstract class.
Faced the same issue in my spring boot application even though I had my package specific scans enabled like
#SpringBootApplication(scanBasePackages={"com.*"})
But, the issue was resolved by providing #ComponentScan({"com.*"}) in my Application class.
Correct way shall be to autowire AbstractManager, as Max suggested, but this should work fine as well.
#Autowired
#Qualifier(value="mailService")
public MailManager mailManager;
and
#Component("mailService")
#Transactional
public class MailManager extends AbstractManager {
}
Can you try annotating only your concrete implementation with #Component? Maybe the following answer could help. It is kind of a similar problem. I usually put Spring annotations in the implementation classes.
https://stackoverflow.com/a/10322456/2619091
I ran in to this recently, and as it turned out, I've imported the wrong annotation in my service class. Netbeans has an option to hide import statements, that's why I did not see it for some time.
I've used #org.jvnet.hk2.annotations.Service instead of #org.springframework.stereotype.Service.
The solution that worked for me was to add all the relevant classes to the #ContextConfiguration annotation for the testing class.
The class to test, MyClass.java, had two autowired components: AutowireA and AutowireB. Here is my fix.
#ContextConfiguration(classes = {MyClass.class, AutowireA.class, AutowireB.class})
public class MyClassTest {
...
}
My guess is that here
<context:component-scan base-package="pl.com.radzikowski.webmail" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
all annotations are first disabled by use-default-filters="false" and then only #Controller annotation enabled. Thus, your #Component annotation is not enabled.
One reason BeanB may not exist in the context
Another cause for the exception is the existence of two bean
Or definitions in the context bean that isn’t defined is requested by name from the Spring context
see more this url:
http://www.baeldung.com/spring-nosuchbeandefinitionexception
<context:component-scan base-package="com.*" />
same issue arrived , i solved it by keeping the annotations intact and in dispatcher servlet :: keeping the base package scan as com.*. this worked for me.
Instead of #Autowire MailManager mailManager, you can mock the bean as given below:
import org.springframework.boot.test.mock.mockito.MockBean;
::
::
#MockBean MailManager mailManager;
Also, you can configure #MockBean MailManager mailManager; separately in the #SpringBootConfiguration class and initialize like below:
#Autowire MailManager mailManager
This also happened to me when I had two methods with the same name marked #Bean in different #Configuration classes. It appears that one of the declarations was overriding the other.
If you are testing your controller.
Don't forget to use #WebAppConfiguration on your test class.
I had this happen because I added an autowired dependency to my service class but forgot to add it to the injected mocks in my service unit test.
The unit test exception appeared to report a problem in the service class when the problem was actually in the unit test. In retrospect, the error message told me exactly what the problem was.
I had faced the same problem,
Issue SOlved using below steps:
Check the class/Interface that you are auto wiring
For Interface Business logic we should use #service when it extends the Interface method.
For Dao that is a Database handling class we should use #Repository.
→ We can use #Service, #Repository and #Component annotation effectively and solve this issue very fast.
if you are testing the DAO layer you must use #Autowire annotation like this:
#Autowired
private FournisseurDao fournisseurDao;
Don't inject a repository element in the constructor
I've reproduced similar issue in multi-module project w/ No qualifying bean of type like:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.stockclient.repository.StockPriceRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
and the reason for this error was missing annotation #EnableJpaRepositories in my specific use case.
To clarify: this annotation needs to be added for enabling auto configuration support for Spring Data JPA required to know the path of JPA repositories. By default, it will scan only the main application package and its sub packages for detecting the JPA repositories.
For more details you can refer, for instance, to this article.
Was configuring a non-SpringBoot, non-JPA, Hibernate application and the error was seen with injecting a DAO class implementation defined with #Repository.
Moving the declaration from #Repository to #Component worked. Remember that you would lose some features as mentioned here
i've problems in order to autowire a service in my controller. I've this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private es.unican.meteo.service.UserService es.unican.meteo.controller.MyController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [es.unican.meteo.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
It seems that the userService is not registered, so that, the controller can't get the bean. I thought that my config was ok because it works with the tests. In the tests i have this:
ClassPathXmlApplicationContext("/WEB-INF/app-config.xml");
and i can get the bean ok from the ApplicationContext.xml
My package structure is the following:
es.unican.meteo.controller
|---- MyController.java
es.unican.meteo.service
|---- UserService.java
es.unican.meteo.service.impl
|---- UserServiceImpl.java
.....
WebContent/WEB-INF
|---- MyDispatcherServlet-servlet.xml
|---- app-config.xml
|---- web.xml
.....
The clases:
== UserServiceImpl.java ==
#Service
public class UserServiceImpl implements UserService{
#Autowired
private UserMapper userMapper;
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
== MyController.java ==
#Controller
public class MyController {
#Autowired
private UserService userService;
#RequestMapping(method=RequestMethod.GET, value="/home")
public String handleRequest(){
return "welcome";
}
#RequestMapping(method=RequestMethod.GET, value="/getUsers")
public #ResponseBody List<User> getUsersInJSON(){
return userService.getUsers();
}
}
== web.xml ==
<display-name>Spring MVC</display-name>
<servlet>
<servlet-name>MyDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyDispatcherServlet</servlet-name>
<url-pattern>*.go</url-pattern>
</servlet-mapping>
</web-app>
== app-config.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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="es.unican.meteo" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
p:url="jdbc:derby:C:\tools\derbydb"
p:connectionProperties=""
p:username="APP"
p:password="" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="/mybatis-config.xml" />
</bean>
<bean id="usersMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="es.unican.meteo.dao.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="rolesMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="es.unican.meteo.dao.RoleMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
</beans>
== MyDispatcherServlet.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- Enabling Spring beans auto-discovery -->
<context:component-scan base-package="es.unican.meteo.controller" />
<!-- Enabling Spring MVC configuration through annotations -->
<mvc:annotation-driven />
<!-- Defining which view resolver to use -->
<bean class= "org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
Spring mvc logger trace:
19:38:54,119 DEBUG http-8080-1 support.DefaultListableBeanFactory:430 - Creating instance of bean 'myController'
19:38:54,170 DEBUG http-8080-1 annotation.InjectionMetadata:60 - Found injected element on class [es.unican.meteo.controller.MyController]: AutowiredFieldElement for private es.unican.meteo.service.UserService es.unican.meteo.controller.MyController.userService
19:38:54,174 DEBUG http-8080-1 support.DefaultListableBeanFactory:504 - Eagerly caching bean 'myController' to allow for resolving potential circular references
19:38:54,206 DEBUG http-8080-1 annotation.InjectionMetadata:85 - Processing injected method of bean 'myController': AutowiredFieldElement for private es.unican.meteo.service.UserService es.unican.meteo.controller.MyController.userService
19:38:54,224 DEBUG http-8080-1 support.DefaultListableBeanFactory:217 - Creating shared instance of singleton bean 'userServiceImpl'
19:38:54,226 DEBUG http-8080-1 support.DefaultListableBeanFactory:430 - Creating instance of bean 'userServiceImpl'
19:38:54,234 DEBUG http-8080-1 annotation.InjectionMetadata:60 - Found injected element on class [es.unican.meteo.service.impl.UserServiceImpl]: AutowiredFieldElement for private es.unican.meteo.dao.UserMapper es.unican.meteo.service.impl.UserServiceImpl.userMapper
19:38:54,237 DEBUG http-8080-1 support.DefaultListableBeanFactory:504 - Eagerly caching bean 'userServiceImpl' to allow for resolving potential circular references
19:38:54,256 DEBUG http-8080-1 annotation.InjectionMetadata:85 - Processing injected method of bean 'userServiceImpl': AutowiredFieldElement for private es.unican.meteo.dao.UserMapper es.unican.meteo.service.impl.UserServiceImpl.userMapper
19:38:54,268 INFO http-8080-1 support.DefaultListableBeanFactory:433 - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#56088b29: defining beans [myController,roleService,userServiceImpl,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.web.servlet.view.InternalResourceViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
19:38:54,279 ERROR http-8080-1 servlet.DispatcherServlet:457 - Context initialization failed
I've reviewed some questions about this topic but i don't find a solution to my problem. Maybe i'm skipping something but i don't know certainly. I tried to change the component-scan with no results.
When i try to access to /SPRING-MVC/getUsers.go appears those errors.
I don't know if the beans must be placed in app-config (applicationContext) or in the servlet.xml because it is a little bit confusing...
Thank you
Your configuration is very strange...
First rule out the obvious
I don't see root web application context configuration in your web.xml. Could it be that you forgot to add this piece of code?
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/app-config.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Now a little bit of theory
Bit of Spring theory - Spring uses application context hierarchy for web applications:
top level web application context is loaded by ContextLoaderListener
then there are separate contexts for each DispatcherServlet instances
When a new bean is being instantiated, it can get dependencies either from the context where it is being defined or from parent context. This makes possible to define common beans in the root context (services, DAO, ...) and have the request handling beans in servlet application contexts as each servlet can have its own set of controllers, view handers, ...
Last, but not least - your errors
You are configuring MVC in your root context. That is just wrong. Remove the <mvc: context from there.
You are also registering your controllers in the root context via the <context:component-scan> on your base package. Make the component scan just on the services package or separate your classes into two top level packages core (for the root beans) and servlet (for servlet beans).
Make sure that your UserServiceImpl is in same package as defined in context:component-scan. If it's not, spring will not be able to detect it. Also, try removing value attribute from UserServiceImpl definition, since there is only 1 bean of that type. Spring will be able to autowire it by type.
You need to change the way you have autowired the service in the controller.
Change the following code
#Autowired
private UserService userService;
with following
#Resource(name="userService")
private UserService userService;
Because in the UserServiceImpl you have defined the #Service annotation with alias "userService".
I hope this would resolve your problem. :)
when ever you face such kind of problem kindly check, what is the path for context:component-scan basepackage
it should be root name Like if I am taking com.mike as package name & which contain bean,controller,dao,service folder in its structure then, in such condition you have to follow Like ----context:component-scan basepackaage="com.mike.*"
where * means all the folder (bean,service,dao,controller and theie corresponding classes) will be scaned.
You can use the #Qualifier annotation as follows:
#Autowired
#Qualifier("userService")
private UserService userService;
On first glance the config seems ok, yet there may be some smaller tripwires that might be not that obvious.
a) implemented UserService interface, is it the same as the controller needs? Dumb question, I know, but just be on the safe side.
b) bean name: Try eradicating the value-value (ba-da-tush) from the #Service annotation, its superflous anyway. Or be more specific with the help of an #Qualifier.
c) package scanning: Double check if your implemented service is really within es.unican.meteo. Sometimes its the small things.
Add #Component annotation on your service. It should work fine
I am trying to implement email functionality in my app but I keep getting
No matching bean of type [org.springframework.mail.javamail.JavaMailSenderImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
Can anyone point out what I am doing incorrectly?
The xml config for the bean is:
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<context:annotation-config/>
//...other stuff
<beans:bean id="mailSession" class="org.springframework.jndi.JndiObjectFactoryBean">
<beans:property name="jndiName" value="EmailServer" />
</beans:bean>
<beans:bean id="emailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<beans:property name="session" ref="mailSession"/>
</beans:bean>
EmailServiceImpl class:
#Service
public class EmailServiceImpl implements EmailService {
#Autowired
private JavaMailSenderImpl emailSender;
//more code..
}
I was struggling with this very problem for an email service class coded like:
#Service("emailService")
public class EmailService {
#Autowired private JavaMailSenderImpl mailSender;
...
public void send(...) {
// send logic
}
}
I stumbled across a solution while reading about a related topic. The key point is that JavaMailSender interface is defined in the applicationContext.xml as the Spring JavaMailSenderImpl class.
Step 1: The application context file was modified to include the following bean definition:
<bean id="mailSender"
class="org.springframework.mail.javamail.JavaMailSenderImpl"
p:host="myMailserver.mycompany.com" />
Step 2: The email service class was modified to look like:
#Service("emailService")
public class EmailService {
#Autowired private JavaMailSender mailSender; // Observe the change in the type
...
Voila! Spring is happy. I would though like to hear a proper explanation of the original error.
Thanks to everyone for their responses. I was unable to get the autowiring to work, but I got the overall email solution to work by doing the following:
setup the mailSession in weblogic, with a jndi name of "myMailSession"
add to servlet-context.xml:
<beans:bean id="mailSession" class="org.springframework.jndi.JndiObjectFactoryBean">
<beans:property name="jndiName" value="myMailSession" />
</beans:bean>
<beans:bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<beans:property name="session" ref="mailSession"/>
</beans:bean>
<beans:bean id="emailServiceImpl" class="com.name.here.business.EmailServiceImpl">
<beans:property name="mailSender" ref="mailSender"/>
</beans:bean>
add to web.xml:
<resource-ref>
<description>the email session</description>
<res-ref-name>myMailSession</res-ref-name>
<res-type>javax.mail.Session</res-type>
<res-auth>Container</res-auth>
</resource-ref>
add to weblogic.xml:
<resource-description>
<res-ref-name>myMailSession</res-ref-name>
<jndi-name>myMailSession</jndi-name>
</resource-description>
EmailServiceImpl:
#Service
public class EmailServiceImpl implements EmailService {
private JavaMailSender mailSender;
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
//..other code
}
You need to add <context:annotation-config/> to your config file in order for Spring to autowire annotated beans.
http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-annotation-config
From error message, I can conclude that autowiring is working , but its not able to find the required bean.
Make sure you load all the bean definition files.
Do you have a #Service or similar annotation on your JavaMailSenderImpl class itself? This will cause Spring's component scanner to put an instance of it in the spring container, which it can then autowire onto the EmailServiceImpl.
This is how I fixed it:
I ran into this issue too, I tried to follow simple tutorials online that worked perfectly during testing by loading the app-context.xml file manually but when I tried to run my spring mvc app it kept showing this error:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.springframework.mail.javamail.JavaMailSender] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:952)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:821)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:735)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 42 more
After trying all kinds of things, I happened to move these two lines from my JPA/DB configuration file to the bottom of my root-config file.
<context:annotation-config/>
<context:component-scan base-package="my.app.service.layer"/>
I'm still learning Spring but I'm thinking there was an issue regarding the order in which they appear.
Edit:
This question seems to clarify the issue with the order:
Difference between applicationContext.xml and spring-servlet.xml in Spring Framework
I'm trying to load bean runtime configuration.
#Stateless
public class MyBean implements MyLocal{
#Resource String runtimeSetting1="default_value";
//....
}
I cannot find out how to create custom resource on app server side (Glassfish) - I have no idea what I should enter in "Factory Class" field.
Maybe there is a better way of loading configuration...
Thanks.
To my knowledge, the standard way in Java EE is to declare env-entry for configuration data. This applies to all Java EE components like EJB 3 bean class, servlet, filters, interceptors, listener classes, etc. Here, declare something like this in your ejb-jar.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd">
<enterprise-beans>
<session>
<ejb-name>FooBean</ejb-name>
<env-entry>
<description>foobar entry</description>
<env-entry-name>foo</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>bar</env-entry-value>
</env-entry>
...
</session>
...
</enterprise-beans>
....
</ejb-jar>
Then look up the env-entry with JNDI or inject it by its name. For example, to inject it in your bean:
#Resource(name="foo")
private String myProperty;