No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' is defined - spring

i am trying to run full package of junit test classes, and i have an audit classes for my domain classes as follows:
#PrePersist
public void prePersist(AuditableEntity e) {
UserService userService = SpringBeanFactory.getBean(UserService.class);
// some auditing here
}
- SpringBeanFactory class:
public class SpringBeanFactory {
private static ApplicationContext applicationContext;
public static <T> T getBean(final String name, final Class<T> requiredType) {
T bean = null;
if (applicationContext != null) {
bean = applicationContext.getBean(name, requiredType);
}
return bean;
}
public static <T> T getBean(final Class<T> requiredType) {
T bean = null;
if (applicationContext != null) {
bean = applicationContext.getBean(requiredType);
}
return bean;
}
public static void setApplicationContext(final ApplicationContext applicationContext) {
if (SpringBeanFactory.applicationContext == null) {
SpringBeanFactory.applicationContext = applicationContext;
}
}
}
-Test class config:
#Autowired
private ApplicationContext applicationContext;
#Before
public void before() throws Exception {
SpringBeanFactory.setApplicationContext(applicationContext);
}
-SpringTestingConfig class:
#Configuration
#ComponentScan(basePackages = "com.myapp.data", excludeFilters = { #Filter(Configuration.class) })
#PropertySource("classpath:/test.properties")
#Profile("test")
public class SpringTestingConfig {
private static Logger log = (Logger)LoggerFactory.getLogger(SpringTestingConfig.class);
#Autowired
private ApplicationContext applicationContext;
#Bean
public DataSource XdataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
if(log.isDebugEnabled()) log.debug("profile.name", "test");
System.setProperty("profile.name", "test");
dataSource.setDriverClassName("org.h2.Driver");
String schemaName = ConfigurationUtil.config().getString("db.schema.name").toLowerCase();
log.debug("SCHEMA IS " + schemaName);
String url = "jdbc:h2:mem:test;MODE=Mysql;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;INIT=CREATE SCHEMA IF NOT EXISTS " +schemaName +"\\;" + "SET SCHEMA "+schemaName;
dataSource.setUrl(url);
//dataSource.setUrl("jdbc:h2:mem:test;MODE=Mysql;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;INIT=CREATE SCHEMA IF NOT EXISTS " + schemaName);
dataSource.setUsername("sa");
//use your own local mysql in tests here...
// dataSource.setDriverClassName("com.mysql.jdbc.Driver");
// dataSource.setUrl("jdbc:mysql://localhost:3306/mv_tests?characterEncoding=UTF-8");
// dataSource.setUsername("tomcat");
// dataSource.setPassword("tomcat");
//
return dataSource;
}
#Bean
public DataSource dataSource() {
SpringBeanFactory.setApplicationContext(applicationContext);
LoggerUtils.setAllApplicationLogs("DEBUG");
DriverManagerDataSource dataSource = new DriverManagerDataSource();
if(log.isDebugEnabled()) {
log.debug("profile.name", "test");
}
System.setProperty("profile.name", "test");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
String schemaName = ConfigurationUtil.config().getString("db.schema.name");
String username = ConfigurationUtil.config().getString("db.username");
String password = ConfigurationUtil.config().getString("db.password");
if( log.isDebugEnabled() ) {
log.debug( "SCHEMA IS " + schemaName );
log.debug( "Username IS " + username );
log.debug( "Password IS " + password );
}
dataSource.setUrl("jdbc:mysql://localhost:3306/"+schemaName);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
-Test class annotations:
#RunWith(SpringJUnit4ClassRunner.class)
#TestExecutionListeners({ WebContextTestExecutionListener.class, DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class })
#ActiveProfiles("test")
#DirtiesContext
#ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { SpringConfig.class, SpringTestingConfig.class, SpringLocalContainerJPAConfig.class, CustomConfiguration.class })
#Transactional
when my test method tries to save an entity, it makes call to PrePersist method which in turn makes call to the getting spring service:
UserService userService = SpringBeanFactory.getBean(UserService.class);
which in turns produces the following exception:
Error creating bean with name 'userService':
Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private com.motivosity.data.repository.UserRepository com.motivosity.service.impl.UserServiceImpl.userRepository;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepositoryImpl':
Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'springLocalContainerJPAConfig': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field:
javax.sql.DataSource com.motivosity.data.config.SpringLocalContainerJPAConfig.dataSource;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'springTestingConfig': Initialization of bean failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'org.springframework.cache.annotation.ProxyCachingConfiguration':
Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' is defined
i have to mention that this exception occurs when running full package of test classes, but when running this test class separately no exception is produced.
BTW, i am using spring 3.2.3.RELEASE
UPDATE: when i upgraded the spring version to latest release 4.0.3, i am getting a new exception on the same get UserService line:
org.springframework.context.support.GenericApplicationContext#3aa54263 has been closed already
please advise how to fix this exception.

When you annotate a test class or test method with #DirtiesContext, you are telling Spring to close the ApplicationContext after that test class or method. Thus, if you later attempt to retrieve a bean from a closed context you will get an exception like you're seeing.
My guess is that you are using #DirtiesContext in other test classes within your test suite, and a result the logic in SpringBeanFactory.setApplicationContext() is broken since it can potentially maintain a reference to a closed context. Thus, you'll need allow the current ApplicationContext to be set for each test. In other words, remove the null-check like follows
public static void setApplicationContext(final ApplicationContext applicationContext) {
// always set the current context
SpringBeanFactory.applicationContext = applicationContext;
}
Hope this helps!
- Sam (author of the Spring TestContext Framework)

Related

Error Coming in Autowiring in Spring

I had put Package name in component scan and #component also , but still error is coming . The code is below.
Here is the SpringConfig file:-
#Configuration
#ComponentScan(basePackages={"com.cagataygurturk.example.lambda","com.cagataygurturk.example.services"})
public class SpringConfig {
}
Here is the Service Class:-
#Component
public class Service {
/**
* Autowiring another Spring Bean
*/
#Autowired
AnotherService anotherService;
public String getText(String text) {
//return anotherService.getText(text);
return "hello";
}
}
Here is the AnotherService class which is autowired in service class:-
#Component
public class AnotherService {
#Autowired
IFileStoreService file;
public String getText(String text) {
String t;
t=(String)text;
if(t.equals("get"))
{
file.get("1");
return "You are in Get Controller and database is not connected\n";
}
else
if(t=="post")
{
return "You are in post Controller and databse is not connecte\n";
}
else
if(t=="delete")
{
return "You are int delete Controller and mongo database in not connected\n";
}
else
{
return "hii\n"+text+"hey";
}
}
}
Here is the IFileStoreService class autowired in AnotherService class:
public interface IFileStoreService {
Resource get(String id) throws StorageException, StorageFileNotFoundException;
}
Here is the IFileStoreImpl class:-
#Component
public class FileStoreServiceImpl implements IFileStoreService {
private static final Logger logger = LoggerFactory.getLogger(FileStoreServiceImpl.class);
#Autowired
private IFileStoreDAO fileStoreDAO;
#Autowired
private StorageProperties storageProperties;
#Override
public Resource get(String id) throws StorageException, StorageFileNotFoundException {
Resource resource = null;
File file = null;
try {
FileDetails fileDetails = fileStoreDAO.get(id);
if(fileDetails != null) {
String tempDir = storageProperties.getLocation();
file = new File(tempDir + File.separator + fileDetails.getName());
file.mkdirs();
if(file.exists()) {
// p1: delete any file if existent in the directory;
file.delete();
}
file.createNewFile();
FileCopyUtils.copy(fileDetails.getFileBytes(), file);
resource = new UrlResource(Paths.get(tempDir).resolve(fileDetails.getName()).toUri());
} else {
throw new StorageFileNotFoundException("No document found with id: " + id);
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
if (e instanceof StorageFileNotFoundException) {
throw (StorageFileNotFoundException) e;
} else {
throw new StorageException("", e);
}
}
return resource;
}
}
And last MainHandler function:-
#SuppressWarnings("unused")
public class MainHandler
extends AbstractHandler<SpringConfig>
implements RequestHandler<Map<String,Object>, String> {
static final Logger log = Logger.getLogger(MainHandler.class);
#Override
public String handleRequest(Map<String, Object> input, Context context)throws RuntimeException {
// TODO Auto-generated method stub
Service businessService = getApplicationContext().getBean(Service.class);
return businessService.getText("hii");
}
}
and the Error is :-
{"errorMessage":"Error creating bean with name 'service': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.cagataygurturk.example.services.AnotherService com.cagataygurturk.example.services.Service.anotherService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'anotherService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.cagataygurturk.example.services.IFileStoreService com.cagataygurturk.example.services.AnotherService.file; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileStoreServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.cagataygurturk.example.services.IFileStoreDAO com.cagataygurturk.example.services.FileStoreServiceImpl.fileStoreDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.cagataygurturk.example.services.IFileStoreDAO] 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)}","errorType":"org.springframework.beans.factory.BeanCreationException"}
As the exception stacktrace suggests:
No qualifying bean of type [com.cagataygurturk.example.services.IFileStoreDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
That means that the class IFileStoreDAO does not have an implementation (I'm not 100% sure on this, might get different exception), or missing #Component annotation, or not being scanned by Spring as a component by being in packages not declared under #ComponentScan(basePackages={"com.cagataygurturk.example.lambda","com.cagataygurturk.example.services"}).
For more information regarding Spring Boot component scanning, see this answer: https://stackoverflow.com/a/33619632/5229041

Spring and ServletContextListener

I read some articles and posts here about
#Autowired
ServletContext context;
Of my realization of ServletContextListener to #Controller. But I got a long exception when run it:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'trendsoftCtrl':
Unsatisfied dependency expressed through field 'context':
No qualifying bean of type [javax.servlet.ServletContext] found for dependency [javax.servlet.ServletContext]:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)};
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [javax.servlet.ServletContext] found for dependency [javax.servlet.ServletContext]:
expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
Here are my classes.
#WebListener
public class TRSCListner implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
String beanFileName = context.getInitParameter("springBeans");
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load(beanFileName);
ctx.refresh();
NewsDao newsDao = ctx.getBean("newsDao", NewsDao.class);
context.setAttribute("appContext", ctx);
context.setAttribute("dao", newsDao);
}
#Override
public void contextDestroyed(ServletContextEvent event) {
ServletContext context = event.getServletContext();
GenericXmlApplicationContext ctx = (GenericXmlApplicationContext) context.getAttribute("appContext");
ctx.close();
}
}
And another
#Controller
public class TrendsoftCtrl {
#Autowired
ServletContext context;
#RequestMapping ("/welcome")
public ModelAndView helloWorld() {
NewsDao newsDao = (NewsDao) context.getAttribute("dao");
List<News> news = newsDao.getAll();
StringBuilder message = new StringBuilder();
for (News n : news) {
message.append(n.getCategory().getName() + "<br>");
message.append(n.getName() + "<br>");
message.append(n.getData() + "<br><br>");
}
return new ModelAndView("welcome", "news", message.toString());
}
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this.context = context;
}
}
By default, the #Autowired will perform the dependency checking to make sure the property has been wired properly. When Spring can’t find a matching bean to wire, it will throw an exception. To fix it, you can disable this checking feature by setting the “required” attribute of #Autowired to false.
#Autowired(required=false)
Even if Spring can’t find a matching bean, it will leave the person property unset.

MongoDB and Spring JPA integration is throwing error

I am trying to integrate Spring JPA with MongoDB. My intention is to just retrieve data from mongo DB. I am getting the below error while injecting my repository.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.org.coop.society.data.mongo.repositories.MaterialMasterRepository com.org.coop.security.service.MongoService.materialMasterRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'materialMasterRepository': Invocation of init method failed; nested exception is java.lang.AbstractMethodError
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
My configuration snippet is given below.
TestMongoDBConfig.java
#Configuration
#EnableMongoRepositories(basePackages = {"com.abc.data.mongo.repositories"})
#ComponentScan(basePackages = "com.abc")
#PropertySource("classpath:applicationTest.properties")
public class TestMongoDBConfig extends AbstractMongoConfiguration {
#Autowired
private Environment env;
#Override
protected String getDatabaseName() {
return "retail";
}
#Override
#Bean
public MongoClient mongo() throws Exception {
MongoClient client = new MongoClient("localhost", 27017);
return client;
}
#Override
protected String getMappingBasePackage() {
return "com.abc.data.mongo.entities";
}
#Bean
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongo(), getDatabaseName());
}
}
MaterialMaster.java in com.abc.data.mongo.entities package
#Document(collection = "materialMaster")
public class MaterialMaster {
#Id
private Long materialId;
#Field
private String name;
MaterialMasterRepository.java in com.abc.data.mongo.repositories package
public interface MaterialMasterRepository extends MongoRepository<MaterialMaster, Long> {
}
MongoService.java in com.abc.service package
#Service
public class MongoService {
#Autowired
private MaterialMasterRepository materialMasterRepository;
public void getMaterials() {
List<MaterialMaster> materials = materialMasterRepository.findAll();
System.out.println(materials);
}
}
Junit class looks like below
#RunWith(SpringJUnit4ClassRunner.class)
#ComponentScan(basePackages = "com.abc")
#ContextHierarchy({
#ContextConfiguration(classes={TestMongoDBConfig.class})
})
public class ModuleWSTest {
#Autowired
private MongoService mongoService;
#Test
public void testModule() {
mongoService.getMaterials();
}
}
I have tried all possible changes (as per my knowledge) but no luck. Any help is really appreciated.
The error message is little confusing. I was using latest spring-data-mongodb (1.8.4.RELEASE). Once I downgraded the dependency to 1.6.0.RELEASE then the above configuration started working.

Unable to autowire dozer Mapper in component class in spring boot

I am new to Spring Boot. I was trying to develop small application in spring boot mvc with neo4j database. Following is my Server
#Configuration
#ComponentScan({ "myproject" })
#EnableAutoConfiguration
#EnableNeo4jRepositories(basePackages = "myproject")
public class Server extends Neo4jConfiguration implements CommandLineRunner
{
public Server()
{
setBasePackage("myproject");
}
#Bean
SpringRestGraphDatabase graphDatabaseService()
{
return new SpringRestGraphDatabase("http://localhost:7474/db/data");
}
#Bean
Mapper mapper()
{
return new DozerBeanMapper();
}
public void run(String... args) throws Exception
{
}
public static void main(String[] args) throws Exception
{
SpringApplication.run(Server.class, args);
}
}
Following is my main class
#Configuration
#ComponentScan({ "myproject.business" })
#EnableNeo4jRepositories(basePackages = "myproject")
public class MainWithStructure extends Neo4jConfiguration implements CommandLineRunner
{
#Autowired
private MyService myService;
public MainWithStructure()
{
setBasePackage("myproject");
}
#Bean
SpringRestGraphDatabase graphDatabaseService()
{
return new SpringRestGraphDatabase("http://localhost:7474/db/data");
}
.......
......
public static void main(String[] args) throws Exception
{
FileUtils.deleteRecursively(new File("accessingdataneo4j.db"));
SpringApplication app = new SpringApplication(MainWithStructure.class);
app.setWebEnvironment(false);
app.run(args);
}
}
Following is my Component class
#Component
public class MyService
{
#Autowired
private Mapper mapper; //Fails to autowire org.dozer.Mapper
.....
}
Following is my Controller class
#RestController
#RequestMapping("/rest")
public class MyController
{
#Autowired
private Mapper mapper; //autowire sucess org.dozer.Mapper
}
I got following Exception when I run main class MainWithStructure
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainWithStructure': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private myproject.business.MyService myproject.main.MainWithStructure.MyService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.dozer.Mapper myproject.business.MyService.mapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.dozer.Mapper] 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)}
Following is my project structure
demo_project
src/main/java
---myproject.main
------MainWithStructure.java
------Server.java
---myproject.business
------MyService.java
---myproject.rest
------MyController.java
If I autowire org.dozer.Mapper in Controller, it sucessfuly autowired it. BUT if I autowire org.dozer.Mapper in Component class it fails to autowire.
Why it is failing to autowire org.dozer.Mapper only on Component class?
Please make me correct if I wrong. Thank you :)
Your Server is not in one of the packages that you #ComponentScan, so the Mapper is indeed not a bean. Try removing the explicit package from the #ComponentScan (since everything is in a subpackage of the main class that will pick up all the components).
You can add #SpringBootApplication in your main class which has #ComponentScan
which will scan all your sub components in project.

Spring Autowire fails with No qualifying bean of type found for dependency error

Here's my scenario. My project is using Spring (3.2.3.RELEASE), Struts2 (2.3.14.3) and JPA (2.0). We have a project (let's call it project A) that contains various entities and common classes. We use project A to generate a .jar file so that other projects can use these classes. In project A we've used the Spring stereotypes: #Component. #Service or #Repository for those classes we want Spring to inject. Whenever we try to inject beans from the jar, we get an error similar to:
No qualifying bean of type
[com.ceiwc.bc.commonsql.service.CommonSQLService] 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)}
Could not autowire field: private com.ceiwc.bc.commonsql.service.CommonSQLService
com.ceiwc.ma.mvc.action.LoginAction.commonSQLService; nested exception
is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[com.ceiwc.bc.commonsql.service.CommonSQLService] 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)}
Error creating bean with name 'com.ceiwc.ma.mvc.action.LoginAction': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private
com.ceiwc.bc.commonsql.service.CommonSQLService
com.ceiwc.ma.mvc.action.LoginAction.commonSQLService; nested exception
is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[com.ceiwc.bc.commonsql.service.CommonSQLService] 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)}
Unable to instantiate Action, com.ceiwc.ma.mvc.action.LoginAction, defined for 'doLogin' in namespace '/Login'Error creating bean with
name 'com.ceiwc.ma.mvc.action.LoginAction': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private
com.ceiwc.bc.commonsql.service.CommonSQLService
com.ceiwc.ma.mvc.action.LoginAction.commonSQLService; nested exception
is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[com.ceiwc.bc.commonsql.service.CommonSQLService] 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)}
We are using Java configuration for Spring. Here is our configuration class:
package com.zzz.bc.config;
#Configuration
#ImportResource({"/WEB-INF/spring/spring-config.xml"})
#ComponentScan(basePackages = "com.zzz")
public class ApplicationConfig {
#Bean
public JavaMailSender mailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(${app.mail.host});
return mailSender;
}
}
package com.zzz.bc.config;
#Configuration
#EnableTransactionManagement
#Import(ApplicationConfig.class)
#PropertySource({"classpath:db.properties"})
public class DataConfig {
#Autowired
Environment environment;
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return transactionManager;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
String[] packagesToScan =
{environment.getProperty("db.packagesToScan1"), environment.getProperty("db.packagesToScan2")};
Map<String, Object> jpaProperties = new HashMap<String, Object>();
jpaProperties.put("eclipselink.weaving", "false");
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPackagesToScan(packagesToScan);
entityManagerFactoryBean.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter());
entityManagerFactoryBean.setJpaPropertyMap(jpaProperties);
return entityManagerFactoryBean;
}
#Bean
public DriverManagerDataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getProperty("db.driver"));
dataSource.setUrl(environment.getProperty("db.url"));
dataSource.setUsername(environment.getProperty("db.username"));
dataSource.setPassword(environment.getProperty("db.password"));
return dataSource;
}
#Bean
public JpaVendorAdapter vendorAdapter() {
EclipseLinkJpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter();
vendorAdapter.setDatabase(Database.ORACLE);
vendorAdapter.setShowSql(true);
return vendorAdapter;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
We have #ComponentScan set to check to bean in the package of com.zzz. In project B, we have a Struts2 Action that we want to inject a bean from project A. Here is a snippet of the class from project B:
#SuppressWarnings("rawtypes")
#Service("CommonSQLService")
public class CommonSQLServiceImpl implements CommonSQLService {
#Autowired
CommonSQLDao cdao;
#Override
public Policy getPolicyById(String policyNo) {
return cdao.getPolicyById(policyNo);
}
#Override
public Policy getPolicy(Policy parmRec) {
return cdao.getPolicy(parmRec);
}
#Override
public ArrayList<Policy> getPolicies(String policyNo) {
return cdao.getPolicies(policyNo);
}
#Override
public List<Policy> getPolicies(Policy parmRec){
return cdao.getPolicies(parmRec);
}
}
Here is our action (removed getters/setters):
package com.zzz.ma.mvc.action;
#SuppressWarnings("serial")
#Component
#Scope("prototype")
#Namespace("/Login")
public class LoginAction extends ActionParent {
#Autowired
private IUserService userService; //Contained in project B
#Autowired
private CommonSQLService commonSQLService; //What's autowired from project A
private User user;
private String updateFlag;
private Integer parentMenuId;
private IwifWebNavmenuItem record;
public static final String LOGIN_STR = "login";
#Action(value = "doLogin", results = { #Result(name = "success", location = "/pages/login.jsp") })
public String login() {
updateFlag = "Y";
return SUCCESS;
}
#Action(value = "validate", results = {
#Result(name = "success", location = "/BrowseOptions/showOptions", type = "redirect"),
#Result(name = "login", location = "/pages/login.jsp") })
public String validateUser() {
if (updateFlag == null) {
session.remove(LOGIN_STR);
return LOGIN;
}
if (userService.validateUser(user.getUsername(), user.getPassword()) == null) {
addActionError(getText("invalid.user"));
return LOGIN;
}
session.put(LOGIN_STR, user.getUsername());
return SUCCESS;
}
#Action(value = "logout", results = { #Result(name = "success", location = "/pages/login.jsp") })
public String logout() {
updateFlag = StringUtils.EMPTY;
session.invalidate();
return SUCCESS;
}
}
Whenever we try to do this autowire, we get an error like the one listed above. What are we missing? Can't classes contained in a jar file with Spring Stereotypes be autowired?
Thanks for you help in advance!
Change #Service("CommonSQLService") to #Service("commonSQLService") or you can just use #Service if you're not implementing the CommonSQLService interface anywhere else.

Resources