How to do integration testing for custom mongo repository? - spring-boot

These are the following configuration that I have done in my project.
#Configuration
public class AppMongoConfig {
#Autowired private MongoDbFactory mongoDbFactory;
#Autowired private MongoMappingContext mongoMappingContext;
#Bean
public MappingMongoConverter mappingMongoConverter() {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
converter.setTypeMapper(new DefaultMongoTypeMapper(null));
return converter;
}
}
#Configuration
#RequiredArgsConstructor
#EnableConfigurationProperties(MultipleMongoProperties.class)
public class MultipleMongoConfig {
private final MultipleMongoProperties mongoProperties;
#Primary
#Bean(name = "primaryMongoTemplate")
public MongoTemplate primaryMongoTemplate() throws Exception {
return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary()));
}
#Bean(name = "secondaryMongoTemplate")
public MongoTemplate secondaryMongoTemplate() throws Exception {
return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary()));
}
#Bean
#Primary
public MongoDbFactory primaryFactory(final MongoProperties mongo) throws Exception {
return new SimpleMongoDbFactory(new MongoClientURI(mongo.getUri()));
}
#Bean
public MongoDbFactory secondaryFactory(final MongoProperties mongo) throws Exception {
return new SimpleMongoDbFactory(new MongoClientURI(mongo.getUri()));
}
}
#Data
#ConfigurationProperties(prefix = "mongodb")
public class MultipleMongoProperties {
private MongoProperties primary = new MongoProperties();
private MongoProperties secondary = new MongoProperties();
}
#Configuration
#EnableMongoRepositories(
basePackages = {"com.student.repository.primary"},
mongoTemplateRef = "primaryMongoTemplate")
public class PrimaryMongoConfig {}
#Configuration
#EnableMongoRepositories(
basePackages = {"com.student.repository.secondary"},
mongoTemplateRef = "secondaryMongoTemplate")
public class SecondaryMongoConfig {}
Repository code:
public interface StudentDAO {
Student save(StudentInfo studentInfo);
}
#Repository
public class StudentDAOImpl implements StudentDAO {
#Autowired #Qualifier("primaryMongoTemplate")
private MongoTemplate mongoTemplate;
#Override public StudentInfo save(StudentInfo userWatchlist) {
return mongoTemplate.save(userWatchlist);
}
}
Integration Testing code:
#RunWith(SpringRunner.class)
#DataMongoTest(includeFilters = #Filter(Repository.class))
public class WatchListDAOImplIT {
#Autowired private StudentDAO studentDAO;
#Test
public void save() {
StudentInfo studentInfo = getStudentInfo();
StudentInfo dbUserWatchlist = watchListDAO.save(studentInfo);
Assert.assertEquals(studentInfo.getId(), dbUserWatchlist.getId());
}
private StudentInfo getStudentInfo() {
StudentInfo studentInfo = new StudentInfo();
studentInfo.setId(9999999l);
return studentInfo;
}
}
Which is giving me following error:-
java.lang.IllegalStateException: Failed to load ApplicationContext
at
org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at
org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
at
org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:
: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'appMongoConfig': Unsatisfied dependency
expressed through field 'mongoDbFactory'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'primaryFactory' defined in class path
resource [.../config/mongo/MultipleMongoConfig.class]: Unsatisfied
dependency expressed through method 'primaryFactory' parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.boot.autoconfigure.mongo.MongoProperties'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations: {}
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'org.springframework.boot.autoconfigure.mongo.MongoProperties'
available: expected at least 1 bean which

Related

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type

2020-09-23T15:28:00.3483912Z java.lang.IllegalStateException: Failed to load ApplicationContext
2020-09-23T15:28:00.3489821Z Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'salecChannelEventProcessor' defined in file [/home/runner/work/calculation-service/calculation-service/target/classes/com/demo/calculation/saleschannel/SalecChannelEventProcessor.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'de.demo.json.schema.JsonValidator' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations:
import de.demo.json.schema.JsonValidator;
#Configuration
#ComponentScan( basePackages = {
"com.demo",
"de.demo" },
excludeFilters = {
#ComponentScan.Filter( Configuration.class )
} )
#ImportResource("classpath:/spring-context.xml")
#Import({SwaggerConfig.class, SalesChannelSqsConfig.class})
public class SpringMvcConfig extends WebMvcConfigurationSupport {
#Autowired private ApplicationContext applicationContext;
#Bean( name = "objectMapper" )
public ObjectMapper getObjectMapper( JacksonService jacksonService ) {
return jacksonService.getObjectMapper();
}
#Bean(name = "jsonValidator")
public JsonValidator jsonValidator() {
return new JsonValidator();
}
}
#Component
#Slf4j
#RequiredArgsConstructor
public class SalesChannelUpdateListerner {
#NonNull
private final SalesChannelService salesChannelService;
#NonNull
private final SalecChannelEventProcessor salecChannelEventProcessor;
#SqsListener(value = "${sales.channel.update.queue.name}", deletionPolicy = ON_SUCCESS)
#SneakyThrows
public void receiveSalesChannelUpdateEvent(
#NotificationMessage EnvelopedMessage envelopedMessage) {
log.debug("Received message from sales channel update event queue : {}"
}
#Component
#Slf4j
#RequiredArgsConstructor
public class SalecChannelEventProcessor {
private static final String MESSAGE_TYPE = "sales_channel_update";
#NonNull
private final ObjectMapper objectMapper;
#NonNull
private final JsonValidator jsonValidator;
#SneakyThrows(JsonProcessingException.class)
public boolean isValid(EnvelopedMessage envelopedMessage) {
if (!MESSAGE_TYPE.equals(envelopedMessage.getType())) {
return false;
}
return jsonValidator.validate(envelopedMessage);
}
You need to create the JsonValidator bean. You need to change yor SalecChannelEventProcessor to be:
#Component
#Slf4j
#RequiredArgsConstructor
public class SalecChannelEventProcessor {
private static final String MESSAGE_TYPE = "sales_channel_update";
#NonNull
private final ObjectMapper objectMapper;
#Bean
public JsonValidator jsonValidator(){
return new JsonValidator();
}
#SneakyThrows(JsonProcessingException.class)
public boolean isValid(EnvelopedMessage envelopedMessage) {
if (!MESSAGE_TYPE.equals(envelopedMessage.getType())) {
return false;
}
return jsonValidator().validate(envelopedMessage);
}
}

Implemetation not found and get a NoSuchBeanDefinitionException

I use spring boot 2 application with spring data jpa and hibernate with postgres
package com.acmor.togy.repository.util.postgres
#Component
public class HStoreParameter implements FormatParameter{
...
}
package com.acmor.togy.repository.util;
public interface FormatParameter {
String format(Map<String, String> properties);
}
package com.acmor.togy.repository.util;
public class AbstractRepository<T, ID> extends SimpleJpaRepository<T, ID> {
private ThreadLocal<Map<String, Object>> parameters = new ThreadLocal<>();
#Autowired
private FormatParameter formatParameter;
public AbstractRepository(JpaEntityInformation entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
}
public AbstractRepository(Class domainClass, EntityManager em) {
super(domainClass, em);
}
}
package com.acmor.togy.repository;
#Repository
public class EnumsRepositoryImpl extends AbstractRepository implements EnumsRepositoryCustom {
}
public interface EnumsRepositoryCustom {
...
}
I created a basic test
#RunWith(SpringRunner.class)
public class EnumsRepositoryCustomTest {
#Autowired
private EnumsRepositoryCustom enumsRepository;
#Test
public void test_advanced_search_using_properties() {
EnumsSearch search = new EnumsSearch();
...
Page<Enums> page = enumsRepository.search(search, PageRequest.of(0, 10));
...
}
}
When I run test I get
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'com.acmor.togy.repository.util.FormatParameter' available: expected
at least 1 bean which qualifies as autowire candidate. Dependency
annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
I have a implementation of FormatParameter, it's HStoreParameter

UnsatisfiedDependencyException: Error creating bean with name

i'm trying to create db server on Spring, and looked through a lot of similar questions, but no one answer to them can't help me. I can't solve this Error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'groupController': Unsatisfied dependency expressed through field 'gs'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'groupServiceImpl': Unsatisfied dependency expressed through field 'gr'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'groupRepository': Cannot create inner bean '(inner bean)#1a3c15e0' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1a3c15e0': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
So here's my classes :
GroupController.java
#RestController
public class GroupController {
#Autowired
private GroupService gs;
#RequestMapping(value = "/groups", method = RequestMethod.GET)
#ResponseBody
public List<Group> getAllGroups(){
// return mocklist();
return gs.getAll();
}
private List<Group> mocklist() {
Group g= new Group();
g.setId(1);
g.setGroupName("333");
g.setTutorName("shcefsa");
List<Group> list = new ArrayList<Group>();
list.add(g);
g.setId(2);
g.setGroupName("333");
g.setTutorName("shc321efsa");
list.add(g);
return list;
}
#RequestMapping(value = "/groups/{id}", method = RequestMethod.GET)
#ResponseBody
public Group getGroupById(#PathVariable("id") int groupId){
return gs.getById(groupId);
}
#RequestMapping(value = "/groups", method = RequestMethod.POST)
#ResponseBody
public Group addGroup(#RequestBody Group group){
return gs.add(group);
}
#RequestMapping(value = "/groups", method = RequestMethod.POST)
#ResponseBody
public Group updateGroup(#RequestBody Group group){
return gs.add(group);
}
#RequestMapping(value = "/groups/{id}", method = RequestMethod.POST)
#ResponseBody
public void deleteGroup(#PathVariable("id") int groupId){
gs.deleteById(groupId);
}
}
GroupRepository.java
#Repository
public interface GroupRepository extends JpaRepository<Group, Integer> {
}
GroupService.java
#Service
public interface GroupService {
List<Group> getAll();
Group getById(int id);
Group add(Group group);
void deleteById(int id);
}
GroupServiceImpl.java`
#Service
public class GroupServiceImpl implements GroupService {
#Autowired
private GroupRepository gr;
public List<Group> getAll() {
return gr.findAll();
}
public Group getById(int id) {
return gr.findOne(id);
}
public Group add(Group group) {
return gr.save(group);
}
public void deleteById(int id) {
gr.delete(id);
}
Looking at other answers, it seems that everything is fine, but it's obvious that there's an error. Hope you'll help me
UPDATE
Databaseconfig.java
#Configuration
#EnableJpaRepositories("com.homestudio.tutor.server.repository")
#EnableTransactionManagement
#PropertySource("classpath:db.properties")
#ComponentScan("com.homestudio.tutor.server")
public class DatabaseConfig {
#Resource
private Environment env;
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(env.getRequiredProperty("db.entity.package"));
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(getHibernateProperties());
return em;
}
#Bean
public PlatformTransactionManager platformTransactionManager(){
JpaTransactionManager manager = new JpaTransactionManager();
manager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return manager;
}
#Bean
public DataSource dataSource(){
BasicDataSource ds = new BasicDataSource();
ds.setUrl(env.getRequiredProperty("db.url"));
ds.setDriverClassName(env.getRequiredProperty("db.driver"));
ds.setUsername(env.getRequiredProperty("db.username"));
ds.setPassword(env.getRequiredProperty("db.password"));
ds.setInitialSize(Integer.valueOf(env.getRequiredProperty("db.initialSize")));
ds.setMinIdle(Integer.valueOf(env.getRequiredProperty("db.minIdle")));
ds.setMaxIdle(Integer.valueOf(env.getRequiredProperty("db.maxIdle")));
ds.setTimeBetweenEvictionRunsMillis(Long.valueOf(env.getRequiredProperty("db.timeBetweenEvictionRunsMilles")));
ds.setMinEvictableIdleTimeMillis(Long.valueOf(env.getRequiredProperty("db.minEvictableIdleTimeMilles")));
ds.setTestOnBorrow(Boolean.valueOf(env.getRequiredProperty("db.testOnBorrow")));
ds.setValidationQuery(env.getRequiredProperty("db.validationQuery"));
return ds;
}
public Properties getHibernateProperties() {
try {
Properties properties = new Properties();
InputStream is = getClass().getClassLoader().getResourceAsStream("hibernate.properties");
properties.load(is);
return properties;
} catch (IOException e) {
throw new IllegalArgumentException("Cannot find file \"hibernate.properties\" in classpath");
}
}
}
WebConfig.java
#Configuration
#EnableWebMvc
#ComponentScan("com.homestudio.tutor.server")
public class WebConfig extends WebMvcConfigurerAdapter{
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(new ObjectMapper());
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
converters.add(converter);
}
}

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.

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