NoSuchBeanDefinitionException while using #Configuration - java

I have weird situation.
I tried to create new bean while using the #Configuration an #Bean this way:
package com.spring.beans.ParkingCar;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class CarMaker
{
#Bean
public CarBean createNewCar()
{
CarBean carBean=new CarBean();
return carBean;
}
}
package com.spring.beans.ParkingCar;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class CarBean
{
private int x = 3;
static Logger logger = Logger.getLogger(CarBean.class);
public void driveCar()
{
logger.debug("I am driving my car" + x);
}
}
and then my test class looks like this:
public static void execute()
{
try
{
PropertyConfigurator.configure("log4j.properties");
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
CarMaker carMaker = (CarMaker) context.getBean("carMaker");
CarBean carBean = carMaker.createNewCar();
carBean.driveCar();
}
catch (Throwable e)
{
logger.error(e);
}
}
my applicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" 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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- Must for auto wiring
<context:annotation-config />
-->
<context:component-scan
base-package="com.spring.beans.ParkingCar">
</context:component-scan>
<aop:aspectj-autoproxy />
<bean id="Spring3HelloWorldBean" class="com.spring.aspect.Spring3HelloWorld">
<property name="myname" value="idan" />
</bean>
<bean id="SecurityAspect" class="com.spring.aspect.SecurityAspect">
</bean>
<bean id="CalculateStrategyBean" class="com.spring.beans.calculator.CalculateStrategyBean">
<constructor-arg value="plus" />
</bean>
<bean id="CalculatorBean" class="com.spring.beans.calculator.CalculatorBean">
<constructor-arg ref="CalculateStrategyBean" />
<constructor-arg ref="CalculateNumbersHolderBean" />
</bean>
<bean id="CalculateNumbersHolderBean" class="com.spring.beans.calculator.CalculateNumbersHolderBean">
<constructor-arg value="10" />
<constructor-arg value="20" />
</bean>
<bean id="lisenceDrive" class="com.spring.beans.ParkingCar.LisenceDrive"
p:carLisenceNum="333" p:isValidateCar="true" />
<bean id="AmbulancelisenceDrive" class="com.spring.beans.ParkingCar.LisenceDrive"
p:carLisenceNum="999" p:isValidateCar="false" />
<bean id="TransitlisenceDrive" class="com.spring.beans.ParkingCar.LisenceDrive"
p:carLisenceNum="111" p:isValidateCar="false" />
<bean id="TransitVechileDetails" class="com.spring.beans.ParkingCar.VechileDetails"
p:modelName="Transit-AS" p:numOfWheels="4" p:year="1992" />
<!-- Wiring without annotations-->
<!--
<bean id="Ambulance"
class="com.spring.beans.ParkingCar.FourWheelsVechile"
p:modelName="GMC" p:numOfWheels="4" p:year="1997"
p:lisenceDrive-ref="AmbulancelisenceDrive" /> <bean id="Bike"
class="com.spring.beans.ParkingCar.TwoWheelsVechile" autowire="byName"
p:modelName="T-BIRD" p:numOfWheels="2" p:year="2012" /> <bean
id="Transit" class="com.spring.beans.ParkingCar.FourWheelsVechile"
p:lisenceDrive-ref="TransitlisenceDrive" autowire="constructor">
-->
<bean id="Ambulance" class="com.spring.beans.ParkingCar.FourWheelsVechile"
p:modelName="GMC" p:numOfWheels="4" p:year="1997" p:lisenceDrive-ref="AmbulancelisenceDrive" />
<!-- Wiring with annotations
<bean id="Bike" class="com.spring.beans.ParkingCar.TwoWheelsVechile"
autowire="byName" p:modelName="T-BIRD" p:numOfWheels="2" p:year="2012" />
<bean id="Transit" class="com.spring.beans.ParkingCar.FourWheelsVechile"
p:lisenceDrive-ref="TransitlisenceDrive">
</bean>
-->
</beans>
Now when I ran it on MyEclipse thru main it worked just fine. but when I uploaded it to my stand alone application which is running on Linux I got:
2012-07-01 14:11:21,152 com.spring.test.Spring3HelloWorldTest [ERROR] org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'carMaker' is defined
Any idea why it didn't work there?
Thanks.

#Configuration indicates that a class declares one or more #Bean methods while #Bean creates a new bean which have same name as the name of the method annotated with #Bean .
In your code sample bean with name createNewCar will be created as method createNewCar() method is annotated by #Bean.
Try this
CarBean carBean = (CarBean) context.getBean("createNewCar");
carBean.driveCar();
Few things to look at
Why to annotate class CarBean as #Configuration? It dont contain any bean defination ie. method with #Bean annotation.
Why to invoke createNewCar() method as it is already annotated with #Bean? (Let Spring do its work)
Check this link it will help you to get familiar with #Configuration and #Bean annotation.

Related

I am trying Spring MVC and when I add #Autowired in my controller class I get following error:

<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<context:component-scan base-package="com.packt.webstore.domain" />
<context:annotation-config></context:annotation-config>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/Webstore"></property>
<property name="username" value="root"></property>
<property name="password" value="password"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'productController': Unsatisfied
dependency expressed through field 'productRepository'; nested
exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'productRepositoryImpl': Unsatisfied
dependency expressed through method 'setDataSource' parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'javax.sql.DataSource' available: expected at
least 1 bean which qualifies as autowire candidate. Dependency
annotations: {}
package com.packt.webstore.domain.repository.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import com.packt.webstore.domain.Product;
import com.packt.webstore.domain.repository.ProductRepository;
#Repository
public class ProductRepositoryImpl implements ProductRepository {
private NamedParameterJdbcTemplate jdbcTemplate;
#Autowired
private void setDataSource(DataSource dataSource) {
this.jdbcTemplate=new NamedParameterJdbcTemplate(dataSource);
}
#Override
public List<Product> getAllProducts() {
Map<String, Object>params=new HashMap<String,Object>();
List<Product>result=jdbcTemplate.query("SELECT * FROM PRODUCTS", params, new ProductMapper());
return result;
}
private static final class ProductMapper implements org.springframework.jdbc.core.RowMapper<Product> {
public Product mapRow(ResultSet rs,int rownum) throws SQLException{
Product product=new Product();
product.setName(rs.getString("name"));
return product;
}
}
}
<?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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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.xsd">
<mvc:annotation-driven enable-matrix-variables="true"></mvc:annotation-driven>
<context:component-scan base-package="com.packt"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
</beans>
package com.packt.webstore.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.packt.webstore.domain.repository.ProductRepository;
#Controller
public class ProductController {
#Autowired
private ProductRepository productRepository;
#RequestMapping("/products")
public String list(Model model) {
model.addAttribute("products",productRepository.getAllProducts());
return "products";
}
}
it looks like you din't configure data-source in xml file
try to add below configuration in xml file
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/yourdbname" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
You need to define DataSource bean in your XML file then only use can use #Autowired annotation to configure that bean or you can use #Autowired annotation in the following way:
#Autowired
private NamedParameterJdbcTemplate jdbcTemplate;

Spring Application loads twice

I'm new to Spring and trying to get a example to work. But my application loads twice each time it starts. I think it could be a context problem because of my internet research and I have just one context.xml.
<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.xsd">
<context:annotation-config/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:environment.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="false"/>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:environment.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="false"/>
</bean>
<bean name="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper" />
<bean name="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="requestFactory" ref="requestFactory" />
</bean>
<bean name="requestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="connectTimeout" value="10000" />
<property name="readTimeout" value="10000" />
</bean>
<bean name="httpClient" class="org.apache.http.client.HttpClient" factory-bean="requestFactory" factory-method="getHttpClient"/>
<bean name="TraderApplication" class="net.mrmoor.TraderApplication"/>
<bean name="API" class="com.iggroup.api.API"/>
<bean name="LightStreamerComponent" class="com.iggroup.api.streaming.LightStreamerComponent"/>
</beans>
My code of the TraderApplication Class is:
... skipped imports ....
#SpringBootApplication
public class TraderApplication implements CommandLineRunner{
private static final Logger log = LoggerFactory.getLogger(TraderApplication.class);
#Autowired
protected ObjectMapper objectMapper;
#Autowired
private API api;
#Autowired
private LightStreamerComponent lightStreamerComponent = new LightStreamerComponent();
private AuthenticationResponseAndConversationContext authenticationContext = null;
private ArrayList<HandyTableListenerAdapter> listeners = new ArrayList<HandyTableListenerAdapter>();
public static void main(String args[]) {
SpringApplication.run(TraderApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
try {
if (args.length < 2) {
log.error("Usage:- Application identifier password apikey");
System.exit(-1);
}
String identifier = args[0];
String password = args[1];
String apiKey = args[2];
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/public-api-client-spring-context.xml");
TraderApplication app = (TraderApplication) applicationContext.getBean("TraderApplication");
app.run(identifier, password, apiKey);
} catch (Exception e) {
log.error("Unexpected error:", e);
}
}
You mention in your comments above you got this working by removing SpringApplication.run(TraderApplication.class, args); but this would be removing spring-boot from your application so I'm going to assume since your question has a tag of [spring-boot] that this is not what you wanted. So here is an alternative way that you can configure beans using your xml.
#ImportResource({"classpath*:public-api-client-spring-context.xml"}) //Proper way to import xml in Spring Boot
#SpringBootApplication
public class TraderApplication implements CommandLineRunner {
...code you had before goes here
#Autowired
TraderApplication app;
#Override
public void run(String... args) throws Exception {
.. your parsing logic here
app.run(identifier, password, apiKey); //Now uses the autowired instance
}
}
You didn't list your pom.xml or build.gradle but it's important to remember that components you have registered in your context xml may be automatically configured in Spring Boot and you may not need to register them yourself in your xml.(Depending on which items you have starters for in your build file)

Spring - what is wrong with my Autowiring?

I've this basic spring application in which the value of my #Autowired field is null in output. What is wrong here?
package com.spring;
import org.springframework.beans.factory.annotation.Autowired;
public class HelloWorld {
private String message;
#Autowired
private Double pi;
public HelloWorld(String message){
this.message = message;
}
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
System.out.println("autowired: "+pi);
}
}
spring.xml config file.
<?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-3.0.xsd">
<bean id="pi" name="pi" class="java.lang.Double" autowire="byName">
<constructor-arg value="3.14"/>
</bean>
<bean id="helloWorld" class="com.spring.HelloWorld">
<constructor-arg ref="msg" />
</bean>
<bean id="msg" class="java.lang.String" >
<constructor-arg value="Hello World"/>
</bean>
</beans>
Class to execute the APP:
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
HelloWorld hw = context.getBean(HelloWorld.class);
hw.getMessage();
System.out.println(context.getBean("msg"));
}
}
The output is:
Your Message Hello World
autowired: null
Hello World
You need to configure the context to allow autowiring. See this answer:
how do I configure autowire in spring
You need to add <context:annotation-config/> in your spring.xml file which will scan for spring annotations in your java files. Hope this helps.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" 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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<bean id="pi" name="pi" class="java.lang.Double">
<constructor-arg value="3.14" />
</bean>
<bean id="helloWorld" class="com.clsa.test.HelloWorld">
<constructor-arg ref="msg" />
</bean>
<bean id="msg" class="java.lang.String">
<constructor-arg value="Hello World" />
</bean>
</beans>
you want to define #Quatifier
#Autowired(required=true)
#Qualifier("pi")
Double pi;

how to convert xml notation to annotation based notation : Spring - Java

I have following xml configuration in my spring context xml, I have used annotation based approach very less and unable to figure out how to represent following using annotation, need help.
<bean id="myPolicyAdmin" class="org.springframework.security.oauth2.client.OAuth2RestTemplate">
<constructor-arg>
<bean class="org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails">
<property name="accessTokenUri" value="${accessTokenEndpointUrl}" />
<property name="clientId" value="${clientId}" />
<property name="clientSecret" value="${clientSecret}" />
<property name="username" value="${policyAdminUserName}" />
<property name="password" value="${policyAdminUserPassword}" />
</bean>
</constructor-arg>
</bean>
In my java class(Policy manager) it is referred as following, I am actually referring a sample and trying to convert it all annotation baesed.
#Autowired
#Qualifier("myPolicyAdmin")
private OAuth2RestTemplate myPolicyAdminTemplate;
EDIT:
I tried creating a bean for org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails but not sure how to set its properties and how to access it as constructor args to myPolicyAdminTemplate
You can configure the same beans using JavaConfig as follows:
#Component
#Configuration
public class AppConfig
{
#Value("${accessTokenEndpointUrl}") String accessTokenUri;
#Value("${clientId}") String clientId;
#Value("${clientSecret}") String clientSecret;
#Value("${policyAdminUserName}") String username;
#Value("${policyAdminUserPassword}") String password;
#Bean
public OAuth2RestTemplate myPolicyAdmin(ResourceOwnerPasswordResourceDetails details)
{
return new OAuth2RestTemplate(details);
}
#Bean
public ResourceOwnerPasswordResourceDetails resourceOwnerPasswordResourceDetails()
{
ResourceOwnerPasswordResourceDetails bean = new ResourceOwnerPasswordResourceDetails();
bean.setAccessTokenUri(accessTokenUri);
bean.setClientId(clientId);
bean.setClientSecret(clientSecret);
bean.setUsername(username);
bean.setPassword(password);
return bean;
}
}
To set the props of a bean you can either use #Value during construction:
How to inject a value to bean constructor using annotations
and this one:
Spring: constructor injection of primitive values (properties) with annotation based configuration
Or #Value in the variables. You could also actually use #Resource, but I wouldn't recommend it.
In your case, the constructor for the
org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails
Would be kinda like
#Autowired
public ResourceOwnerPasswordResourceDetails(
#Value("${accessTokenEndpointUrl}") String accessTokenUri,
#Value("${clientId}") String clientId,
#Value("${clientSecret}") String clientSecret,
#Value("${policyAdminUserName}") String username,
#Value("${policyAdminUserPassword}") String password
)
I shall give you a XML configuration with it anotation based config equivalent respectively, so that you will easily see how to change your bean from xml to java and vice-versa
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.mycompany.backendhibernatejpa.controller" />
<mvc:annotation-driven />
<bean id="iAbonneDao" class="com.mycompany.backendhibernatejpa.daoImpl.AbonneDaoImpl"/>
<bean id="iAbonneService" class="com.mycompany.backendhibernatejpa.serviceImpl.AbonneServiceImpl"/>
<!-- couche de persistance JPA -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="generateDdl" value="true" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:bd.properties"/>
</bean>
<!-- la source de donnéees DBCP -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >
<property name="driverClassName" value="${bd.driver}" />
<property name="url" value="${bd.url}" />
<property name="username" value="${bd.username}" />
<property name="password" value="${bd.password}" />
</bean>
<!-- le gestionnaire de transactions -->
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- traduction des exceptions -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<!-- annotations de persistance -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
</beans>
this file is named springrest-sevlet. actually you can give the name you want followed by "-servlet" and mention that name in the file web.xml
<web-app>
<display-name>Gescable</display-name>
<servlet>
<servlet-name>springrest</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springrest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
the two files should be place in the folder "WEB-INF".
Now the equivalent with anotation based config
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.backendhibernatejpaannotation.configuration;
import com.mycompany.backendhibernatejpaannotation.daoImpl.AbonneDaoImpl;
import com.mycompany.backendhibernatejpaannotation.daoInterface.IAbonneDao;
import com.mycompany.backendhibernatejpaannotation.serviceImpl.AbonneServiceImpl;
import com.mycompany.backendhibernatejpaannotation.serviceInterface.IAbonneService;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
*
* #author vivien saa
*/
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.mycompany.backendhibernatejpaannotation")
public class RestConfiguration {
#Bean
public IAbonneDao iAbonneDao() {
return new AbonneDaoImpl();
}
#Bean
public IAbonneService iAbonneService() {
return new AbonneServiceImpl();
}
// #Bean
// public PropertyPlaceholderConfigurer placeholderConfigurer() {
// PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
// placeholderConfigurer.setLocations("classpath:bd.properties");
// return placeholderConfigurer;
// }
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/gescable");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
#Bean
public HibernateJpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect");
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setShowSql(true);
return jpaVendorAdapter;
}
#Bean
public InstrumentationLoadTimeWeaver loadTimeWeaver() {
InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
return loadTimeWeaver;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource());
entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter());
entityManagerFactory.setLoadTimeWeaver(loadTimeWeaver());
return entityManagerFactory;
}
#Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return jpaTransactionManager;
}
#Bean
public PersistenceExceptionTranslationPostPro`enter code here`cessor persistenceExceptionTranslationPostProcessor() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor() {
return new PersistenceAnnotationBeanPostProcessor();
}
}
this file must be accompanied by this one
package com.mycompany.backendhibernatejpaannotation.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
*
* #author vivien saa
*/
public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RestConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}

Struts 2, Spring Plugin + Shiro integration: Autowiring issue

I have an issue with Struts2(2.3.15.1) Spring plugin. I use Shiro for security, and configure it with Annotations. The code looks like this:
public class Order2Action extends BaseAction {
#Autowired private UserDAO userDAO;
private static final Logger log = LoggerFactory.getLogger(Order2Action.class);
#Action(value = "list2",
results = {#Result(name = SUCCESS, location = "list.jsp")}
)
#RequiresRoles(ROLE_DATA_OPERATOR)
public String showOrderList() throws InterruptedException {
log.info("UserDAOImpl {}", userDAO);
return SUCCESS;
}
}
In this case UserDAO is not injected to Action. But if I comment out the string "#RequiresRoles(ROLE_DATA_OPERATOR)" - UserDAO is injected to Action.
What could be the problem here?
My ApplicationContext conf 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:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- enable processing of annotations such as #Autowired and #Configuration -->
<context:annotation-config/>
<context:component-scan base-package="ee"/>
<bean id="makuDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
...
</bean>
<!--Shiro security configuration -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/maku/auth/login"/>
<property name="unauthorizedUrl" value="/maku/auth/unauthenticated"/>
</bean>
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="shiroCacheMan"/>
<property name="realm" ref="jdbcRealm"/>
</bean>
<bean id="jdbcRealm" class="org.apache.shiro.realm.jdbc.JdbcRealm">
<property name="dataSource" ref="makuDataSource"/>
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.PasswordMatcher"/>
</property>
</bean>
<bean name="shiroCacheMan" class="org.apache.shiro.cache.ehcache.EhCacheManager"/>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!-- Enable Shiro Annotations for Spring-configured beans. Only run after -->
<!-- the lifecycleBeanProcessor has run: -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true" />
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
</beans>
UserDAO:
public interface UserDAO {
User getByUsername(String username);
}
#Repository
public class UserDAOImpl extends AbstractJDBCDAO implements UserDAO {
#Override
public User getByUsername(String username){
return makuTmpl.queryForObject("select id, username, fullname from users where username=?",
new RowMapper<User>() {
#Override
public User mapRow(ResultSet rs, int i) throws SQLException {
User u = new User();
u.setId(rs.getLong( 1 ));
u.setUsername(rs.getString(2));
u.setFullname(rs.getString(3));
return u;
}
}, username);
}
}

Categories