NoSuchBeanDefinitionException on using Aspect - spring

Spring boot version used: 1.2.3
We are creating CacheManager based on a property like :
#Bean
public CacheManager cacheManager() throws IOException {
String cacheImpl = env.getProperty(CacheSupport.CACHE_PROPERTY, String.class, "");
if (CacheSupport.AEROSPIKE.equalsIgnoreCase(cacheImpl)) {
return aerospikeCacheManager();
} else if (CacheSupport.REDIS.equalsIgnoreCase(cacheImpl)) {
return redisCacheManager();
} else {
return guavaCacheManager();
}
}
We have an AerospikeController like below :
#ConditionalOnProperty(name = CacheSupport.CACHE_PROPERTY, havingValue = CacheSupport.AEROSPIKE)
#Controller
public class AerospikeController {
#Autowired
private AerospikeCacheManager aerospikeCacheManager;
}
Things were working fine. Problem arises when i added below code for intercepting response times of aerospike calls:
#Component
#Aspect
public class WebServiceResponseTimeLogger {
private static final Logger LOG = LoggerFactory.getLogger(WebServiceResponseTimeLogger.class);
#Autowired
private AerospikeCacheManager cacheManager;
#PostConstruct
void init() {
LOG.info("WebServiceRequestTimeLogger initialized");
}
public WebServiceResponseTimeLogger() {
super();
}
#Pointcut("execution(* com.snapdeal.pie.web.aerospike.config.AerospikeCacheManager.*(..))")
public void pointcuts() {
}
#Around("pointcuts()")
public void logExternalCalls(ProceedingJoinPoint pjp) throws Throwable {
long timeStartInMillisecs = System.currentTimeMillis();
pjp.proceed();
MethodSignature signature = (MethodSignature) pjp.getSignature();
LOG.info("Time Taken to execute : {} {} is {} ms", new Object[] { signature, pjp.getArgs()[0], (System.currentTimeMillis() - timeStartInMillisecs) });
}
}
I am getting below exception :
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.snapdeal.pie.web.aerospike.config.AerospikeCacheManager] 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:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 18 common frames omitted

From the logs it says :
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.snapdeal.pie.web.aerospike.config.AerospikeCacheManager] 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)}
Check if bean AerospikeCacheManager is created in this code correctly.
#Bean
public CacheManager cacheManager() throws IOException {
String cacheImpl = env.getProperty(CacheSupport.CACHE_PROPERTY, String.class, "");
if (CacheSupport.AEROSPIKE.equalsIgnoreCase(cacheImpl)) {
return aerospikeCacheManager();

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 boot,No qualifying bean of type found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency

#Controller
#EnableAutoConfiguration
public class ControllerShowInfo
{
#RequestMapping("/")
public String rawPage()
{
return "rawPage";
}
#Autowired
stockreviewsRepositoryDao repository;
#RequestMapping("/getBaseInfo")
#ResponseBody
public JSONArray getReviewsInfo()
{
JSONArray jsonArray = new JSONArray();
for (stockreviewsBean reviewBean : repository.findAll())
{
jsonArray.put(reviewBean);
System.out.println(reviewBean.getTitle());
}
return jsonArray;
}
public static void main(String[] args) throws Exception
{
SpringApplication.run(ControllerShowInfo.class, args);
}
}
this is controller layer.
public interface stockreviewsRepositoryDao extends CrudRepository<stockreviewsBean,String>
{
}
this is Dao layer.
when I run ControllerShowInfo.class. There is a problem as follows:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'controllerShowInfo': Unsatisfied dependency expressed through field 'repository': No qualifying bean of type [com.yxzh.mapper.stockreviewsRepositoryDao] found for dependency [com.yxzh.mapper.stockreviewsRepositoryDao]: 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 [com.yxzh.mapper.stockreviewsRepositoryDao] found for dependency [com.yxzh.mapper.stockreviewsRepositoryDao]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:
but when I run another .class
#SpringBootApplication
public class Application
{
public static void main(String[] args) throws Exception
{
SpringApplication.run(Application.class, args);
}
}
and implement CommmandLineRunner
#Component
public class DataInitialization implements CommandLineRunner{
#Autowired
stockreviewsRepositoryDao repository;
#Override
public void run(String... args) throws Exception
{
System.out.println("-------------------------------");
int count=0;
for (stockreviewsBean reviewBean : repository.findAll())
{
count++;
System.out.println(reviewBean.getTitle());
}
System.out.println(count);
}
}
It worked well. It really confused me.
Have you tried to annotate
stockreviewsRepositoryDao with #Repository
and
Application with #EnableJpaRepositories(basePackageClasses = {"stockreviewsRepositoryDao.class"})

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.

spring boot Can not #Autowired dao

I met a question , I try to startup project,bu it's failed
These are my configuration ,dao and service , is anyone can tell me why ,thx a lot
This is DataBaseConfiguration:
#Configuration
#EnableTransactionManagement
public class DataBaseConfiguration implements EnvironmentAware {
private RelaxedPropertyResolver propertyResolver;
private static Logger log = LoggerFactory.getLogger(DataBaseConfiguration.class);
#Override
public void setEnvironment(Environment env) {
this.propertyResolver = new RelaxedPropertyResolver(env, "dataSource.");
}
#Bean(destroyMethod = "close")
public DataSource dataSource() {
log.debug("Configuring DataSource");
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl(propertyResolver.getProperty("url"));
druidDataSource.setDriverClassName(propertyResolver.getProperty("driverClassName"));
druidDataSource.setUsername(propertyResolver.getProperty("username"));
druidDataSource.setPassword(propertyResolver.getProperty("password"));
return druidDataSource;
}
}
This is MybatisConfiguration :
#Configuration
#ConditionalOnClass({ EnableTransactionManagement.class, EntityManager.class})
#AutoConfigureAfter({ DataBaseConfiguration.class })
#MapperScan("com.future.api.**.dao")
public class MybatisConfiguration implements EnvironmentAware {
private static Log logger = LogFactory.getLog(MybatisConfiguration.class);
private RelaxedPropertyResolver propertyResolver;
#Autowired
private DataSource dataSource;
#Override
public void setEnvironment(Environment env) {
this.propertyResolver = new RelaxedPropertyResolver(env, "mybatis.");
}
#Bean
#ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory() {
try {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setTypeAliasesPackage(propertyResolver
.getProperty("typeAliasesPackage"));
sessionFactory
.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(propertyResolver
.getProperty("mapperLocations")));
sessionFactory
.setConfigLocation(new DefaultResourceLoader()
.getResource(propertyResolver
.getProperty("configLocation")));
return sessionFactory.getObject();
} catch (Exception e) {
logger.warn("Could not configure mybatis session factory");
return null;
}
}
#Bean
#ConditionalOnMissingBean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}
This is dao
public interface UserMapper extends BaseDao<User,UserCriteria ,String> {
#SelectProvider(type=UserSqlProvider.class, method="countByExample")
int countByExample(UserCriteria example);
#DeleteProvider(type=UserSqlProvider.class, method="deleteByExample")
int deleteByExample(UserCriteria example);
#Delete({
"delete from t_user",
"where id = #{id,jdbcType=VARCHAR}"
})
int deleteByPrimaryKey(String id);
#Insert({
"insert into t_user (id, username, ",
"password, created_by, ",
"created_date, last_modified_by, ",
"last_modified_date)",
"values (#{id,jdbcType=VARCHAR}, #{username,jdbcType=VARCHAR}, ",
"#{password,jdbcType=VARCHAR}, #{createdBy,jdbcType=VARCHAR}, ",
"#{createdDate,jdbcType=DATE}, #{lastModifiedBy,jdbcType=VARCHAR}, ",
"#{lastModifiedDate,jdbcType=DATE})"
})
int insert(User record);
}
This is service
#Service
#Transactional
public class UserServiceImp extends BaseServiceImpl<User,UserCriteria> implements UserService {
#Autowired
private UserMapper userDao;
#Override
protected BaseDao<User, UserCriteria, String> getDao() {
return userDao;
}
}
This error info
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.future.api.user.dao.UserMapper com.future.api.user.service.imp.UserServiceImp.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.future.api.user.dao.UserMapper] 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.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
... 22 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.future.api.user.dao.UserMapper] 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:1373) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
... 24 common frames omitted
I believe your problem may be this annotation:
#MapperScan("com.future.api.**.dao")
I haven't seen before (in code as well as in documentation) that it would be possible to use wildcards. Try use exact package name.
I believe it scans also sub-packages, so you may want to change package structure to have all DAOs in tree under single package.

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