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.
Related
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
#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 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();
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)
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.