custom spring xd module with spring data elasticsearch: No qualifying bean of type [ElasticsearchTemplate] found - spring-xd

I customed a spring xd processor module,try link to elasticsearch in my module with spring data elasticsearch.
unittest is ok,but when deploy in the singlenode, throw the exception:
- Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.integration.
config.TransformerFactoryBean#0': Cannot create inner bean 'com.eheluo.bigdata.wenxin.ToElasticsearch#0' of type [com.eh
eluo.bigdata.wenxin.ToElasticsearch] while setting bean property 'targetObject'; nested exception is org.springframework
.beans.factory.BeanCreationException: Error creating bean with name 'com.eheluo.bigdata.wenxin.ToElasticsearch#0': Injec
tion of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Coul
d not autowire field: private org.springframework.data.elasticsearch.core.ElasticsearchTemplate com.eheluo.bigdata.wenxi
n.ToElasticsearch.elasticsearchTemplate; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionExcep
tion: No qualifying bean of type [org.springframework.data.elasticsearch.core.ElasticsearchTemplate] found for dependenc
y: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.spr
ingframework.beans.factory.annotation.Autowired(required=true)}
it can't find bean org.springframework.data.elasticsearch.core.ElasticsearchTemplate.
my pom file is:
<parent>
<groupId>org.springframework.xd</groupId>
<artifactId>spring-xd-module-parent</artifactId>
<version>1.1.1.RELEASE</version>
<relativePath></relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>1.2.1.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</exclusion>
</exclusions>
</dependency>
....
my custom module code is :
#Component
public class ToElasticsearch {
private Logger logger = Logger.getLogger(ToElasticsearch.class);
#Autowired
private ElasticsearchTemplate elasticsearchTemplate;
public String process(NewDataInterface data){
NewData newData = new NewData();
BeanUtils.copyProperties(data, newData);
String docid = elasticsearchTemplate.index(genIndexQuery(newData));
logger.debug("save to es");
return docid;
}
my application.properties is :
# options_class=com.eheluo.bigdata.wenxin.ToElasticsearch
# ELASTICSEARCH (ElasticsearchProperties})
# The cluster name (defaults to elasticsearch)
spring.data.elasticsearch.cluster-name=elasticsearch
# The address(es) of the server node (comma-separated; if not specified starts a client node)
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
# if spring data repository support is enabled
spring.data.elasticsearch.repositories.enabled=true
my module.properties has nothing to export options
my module.xml is :
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd
">
<channel id="input"/>
<transformer input-channel="input" output-channel="output">
<beans:bean class="com.eheluo.bigdata.wenxin.ToElasticsearch" />
</transformer>
<channel id="output"/>
</beans:beans>
my unittest is :
public class ToElasticsearchTest {
private static SingleNodeApplication application;
private static int RECEIVE_TIMEOUT = 5000;
private static String moduleName = "toelasticsearch";
#BeforeClass
public static void setUp() {
RandomConfigurationSupport randomConfigSupport = new RandomConfigurationSupport();
application = new SingleNodeApplication().run();
SingleNodeIntegrationTestSupport singleNodeIntegrationTestSupport = new SingleNodeIntegrationTestSupport(application);
singleNodeIntegrationTestSupport.addModuleRegistry(new SingletonModuleRegistry(ModuleType.processor, moduleName));
}
#Test
public void test() {
String streamName = "toElasticsearchTest";
String newID = UUID.randomUUID().toString();
NewDataInterface newData = new NewDataPOJO();
newData.setsomthing("testtesttest");
newData.setId(newID);
Multiset<String> words = ConcurrentHashMultiset.create();
words.add("1");
words.add("2");
words.add("3");
words.add("4", 2);
newData.setsomthinx(words);
String processingChainUnderTest = moduleName;
SingleNodeProcessingChain chain = chain(application, streamName, processingChainUnderTest);
chain.sendPayload(newData);
String result = (String) chain.receivePayload(RECEIVE_TIMEOUT);
assertEquals(newID, result);
chain.destroy();
}
}
unit test is always ok:Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
but can't work in singlenode rutime.
why it can't find ElasticsearchTemplate in runtime?

Related

Depending on maven dependency scope compiled or provided produces Ambiguous Bean or ClassNotfoundException

Environment:
Java 11
JBoss 7.2
Maven 3.5
I have a project with many maven modules and a common for all. Depend on the scope of dependency compile or provided I am getting WELD-001414: Bean name is ambiguous or java.lang.ClassNotFoundException.
How to solve these two errors to once?
When pom.xml (app-back) has dependency app-commons
When app-commons is scope provided
ERROR java.lang.ClassNotFoundException: net.sf.jasperreports.engine.JRException
When app-commons is scope compiled
ERROR WELD-001414: Bean name is ambiguous. Name version resolves to beans: [Managed Bean [class es.caib.app.commons.utils.Version] with qualifiers [#Default #Any #Named], Managed Bean [class es.caib.app.commons.utils.Version] with qualifiers [#Default #Any #Named]]"}}
Modules:
app (pom)
app-ear
app-back (dependency to app-commons)
app-front (dependency to app-commons)
app-commons (jasperreport dependency)
...
app-commons have ReportManager.java that needs jasper dependency and Version.java of type #ApplicationScope
pom.xml app-commons
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>es.caib.accfor</groupId>
<artifactId>app</artifactId>
<version>8.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>app-commons</artifactId>
<packaging>jar</packaging>
<name>app-commons</name>
...
<dependencies>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.15.0</version>
</dependency>
</dependencies>
...
Version.java (app-commons)
...
#Named
#ApplicationScoped
public class Version {
private String version;
private String buildTime;
private String scmRevision;
private String jdkVersion;
private String projectName;
...
ReportManager.java (app-commons)
public class ReportManager {
...
public static void addParam(Map<String, Object> params, String nom, byte[] compiledReport) throws ReportException {
try {
params.put(nom, SerializationUtils.deserialize(compiledReport));
} catch (Exception e) {
throw new ReportException("Error deserialize compiledReport.");
}
}
...
In app-back module I call ReportManager.addParam()
SessionScoped.java (app-back)
#Named
#SessionScoped
public class SessionBean implements Serializable {
#Inject
private Version version;
...
StartupListener.java (app-back)
#WebListener
public class StartupListener implements ServletContextListener {
private static final Logger LOG = LoggerFactory.getLogger(StartupListener.class);
#Inject
private Version version;
...
Because of transitive dependencies are not included when dependency is provided, so I had to restructure the modules this way.
Modules:
app (pom)
app-ear
jasperreports (compiled) MOVED FROM APP-COMMONS
app-back
app-commons (provided)
app-front
app-commons (provided)
app-commons
...
I was not able to change app-commons dependency to compiled because it is dependent of app-front and app-back. In app-commons as compiled I have an #ApplicationScope class that it would produce ambiguous Beans pointing to the class in app-commons because of jakartaee context management.

JedisConnectionFactory bean instantiation failure during application startup and throws java.lang.NullPointerException

I am using spring-boot-data, redis and jedis. I created jedisConnectionFactory and redisTemplate beans in a Configuration class. JedisConnectionFactory bean instantiation failure during application startup.
I use the latest libraries. This is the exception I get:
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-
maven-plugin:2.2.0.BUILD-SNAPSHOT:run (default-cli) on project
Console: An exception occurred while running. null:
InvocationTargetException: Error creating bean with name
'consoleApplication': Unsatisfied dependency expressed through field
'bookRepository'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'bookRepository': Cannot resolve reference
to bean 'redisKeyValueTemplate' while setting bean property
'keyValueOperations'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'redisKeyValueTemplate': Cannot resolve
reference to bean 'redisKeyValueAdapter' while setting constructor
argument; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'redisKeyValueAdapter': Cannot resolve
reference to bean 'redisTemplate' while setting constructor
argument; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'redisTemplate' defined in class path
resource [com/console/config/AppConfig.class]: Bean instantiation
via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [org.springframework.data.redis.core.RedisTemplate]:
Factory method 'redisTemplate' threw exception; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'jedisConnectionFactory' defined in class
path resource [com/console/config/AppConfig.class]: Bean
instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [org.springframework.data.redis.connection.jedis.JedisConnectionFactory]: Factory method 'jedisConnectionFactory' threw exception; nested exception is java.lang.NullPointerException -> [Help 1]
This is my pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<!-- <version>2.2.0.BUILD-SNAPSHOT</version> -->
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<!-- <version>3.0.1</version> -->
<!-- <type>jar</type> -->
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
This is my code:
#Configuration
public class AppConfig {
#Autowired
private RedisProperties redisProperties;
#Bean
JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(redisProperties.getHost(), redisProperties.getPort());redisStandaloneConfiguration.setPassword(redisProperties.getPassword());
JedisClientConfiguration.JedisClientConfigurationBuilder builder = JedisClientConfiguration.builder()
.connectTimeout(redisProperties.getTimeout())
.readTimeout(redisProperties.getJedis().getPool().getMaxWait());
if (redisProperties.isSsl())
builder.useSsl();
// Final JedisClientConfiguration
JedisClientConfiguration clientConfig = builder.build();//.usePooling().build();
return new JedisConnectionFactory(redisStandaloneConfiguration, clientConfig);
}
#Bean
public RedisTemplate<Object, Object> redisTemplate() {
RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
JedisConnectionFactory factory = jedisConnectionFactory();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
}
#Repository
public interface BookRepository extends CrudRepository<Book, Long> {
}
I expect the simple application to run without exception.
Any advice and insight is appreciated.
From reviewing JedisConnectionFactory code it seem like you can get such error only if one of the arguments to the Ctor is null.
public JedisConnectionFactory(RedisStandaloneConfiguration standaloneConfig, JedisClientConfiguration clientConfig) {
this(clientConfig);
Assert.notNull(standaloneConfig, "RedisStandaloneConfiguration must not be null!");
this.standaloneConfig = standaloneConfig;
}
I had the same problem. For me, the problem was the order in which the beans were created.
It's important that the jedisConnectionFactory bean is created before any of its dependencies. A way of telling Spring about this is by using the #DependsOn annotation. You could do something like this:
#SpringBootApplication
#DependsOn("jedisConnectionFactory")
public class Application extends SpringBootServletInitializer {
...
}
There are probably better ways of solving this! My suggestion is just a workaround.

Error creating bean with name 'xxx'

I'm having issues with dependency injection.
I've tried both #EJB and #Autowired, but nothing works.
This is what i have now:
HomeController
#Controller
#ComponentScan(basePackages = "org.vives.repositories")
public class HomeController extends HttpServlet {
private final BeerRepository beerRepository;
#Autowired
public HomeController(BeerRepository beerRepository) {
this.beerRepository = beerRepository;
}
#GetMapping("/")
public String index(Model model) {
List<Brewer> brewers = this.beerRepository.getAll();
model.addAttribute("brewers", brewers);
return "index";
}
}
When I hover over beerRepository parameter, I get that:
BeerRepository
#Stateless
#Repository
public class BeerRepository {
#PersistenceContext(unitName = "vivesPU")
private EntityManager entityManager;
public List<Brewer> getAll() {
List<Brewer> brewers = new ArrayList<>();
Brewer br0 = new Brewer("WESTVLETEREN BREWERY");
Brewer br1 = new Brewer("BRASSERIE CANTILLON");
Brewer br2 = new Brewer("RODENBACH BREWERY");
Brewer br3 = new Brewer("KULMINATOR");
Brewer br4 = new Brewer("‘T BRUGS BEERTJE");
brewers.add(br0);
brewers.add(br1);
brewers.add(br2);
brewers.add(br3);
brewers.add(br4);
return brewers;
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="vivesPU" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>jdbc/beers</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyTenSevenDialect"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
Error log (some of it)
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController' defined in file [..\HomeController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beerRepository': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'vivesPU' available
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beerRepository': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'vivesPU' available
...
Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'vivesPU' available]]
vivesPU is the persistance-unit name, so why would it even go there?
project structure
Can someone explain to me what is happening? I'm really confused. Most of the documentation and posts are old (Spring 4 and Spring XML) which are barely relevant.
Either you have to autowire BeerRepository or remove the below line
private final BeerRepository beerRepository;
Your controller is completely false. It should be
#Controller
#ComponentScan(basePackages = "org.vives.repositories")
public class HomeController extends HttpServlet {
#Autowired
private BeerRepository beerRepository;
#GetMapping("/")
public String index(Model model) {
List<Brewer> brewers = beerRepository.getAll();
model.addAttribute("brewers", brewers);
return "index";
}
}

How to link database in mongodb through spring

I really need some help, I have gone through an entire day of searching and still did not find anything that works.
Note : My database has username and password
And these two are the dependencies that i am working with.
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
This is my xml config file :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<mongo:mongo-client host="address" port="27017 credentials="username:password#databasename" />
</beans>
This is my main class which loads this xml:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import model.user;
//import org.springframework.context.support.GenericXmlApplicationContext;
public class App {
public static void main(String[] args) {
/*
ApplicationContext ctx = new AnnotationConfigApplicationContext(appConfig.class);
MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
*/
ApplicationContext ctx = new GenericXmlApplicationContext("config.xml");
MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");
user user = new user();
// save
// mongoOperation.save(user);
// now user object got the created id.
System.out.println("1. user : " + user);
// query to search user
Query searchUserQuery = new Query(Criteria.where("age").is(26));
mongoOperation.findOne(searchUserQuery, user.class);
}
}
This is the error message I get:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongo': Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: com.mongodb.MongoCredential.createCredential(Ljava/lang/String;Ljava/lang/String;[C)Lcom/mongodb/MongoCredential;
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:687)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.context.support.GenericXmlApplicationContext.<init>(GenericXmlApplicationContext.java:70)
at core.App.main(App.java:20)
Caused by: java.lang.NoSuchMethodError: com.mongodb.MongoCredential.createCredential(Ljava/lang/String;Ljava/lang/String;[C)Lcom/mongodb/MongoCredential;
at org.springframework.data.mongodb.config.MongoCredentialPropertyEditor.setAsText(MongoCredentialPropertyEditor.java:108)
at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:430)
at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:403)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:181)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:460)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:512)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:506)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1503)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1462)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1198)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
... 10 more
Okay finally I was able to connect to the database, I did it using MongoClient. This is the code snippet:
MongoCredential credential = MongoCredential.createMongoCRCredential("username", "database", password);
MongoClient mongoClient = new MongoClient(new ServerAddress("address", 27017), Arrays.asList(credential));
// get handle to "mydb"
DB db = mongoClient.getDB("IODS");
// get a list of the collections in this database and print them out
Set<String> collectionNames = db.getCollectionNames();
for (final String s : collectionNames) {
System.out.println(s);
}
// get a collection object to work with
DBCollection coll = db.getCollection("try_vishal");

Junit Test failing due to Parent applicationContext bean

My test case is failing with the below error :
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'acesFormFactory' defined in class path resource [/META-INF/aces-beans.xml]: Cannot resolve reference to bean 'promotionMarshaller' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'promotionMarshaller' is defined
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:629)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:148)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1049)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
Now here is my Test Class :
#WebAppConfiguration
#ContextConfiguration(locations = {
"classpath:/META-INF/aces-beans.xml",
"classpath:/META-INF/aces-flow-config.xml" })
#RunWith(SpringJUnit4ClassRunner.class)
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class })
public class ApplicationContextTest {
#Resource
private AcesFormFactory acesFormFactory;
#Test
public void paymentFormFactoryAvailable() {
assertThat(acesFormFactory, is(notNullValue()));
assertThat(acesFormFactory, is(instanceOf(AcesFormFactoryImpl.class)));
}
}
Here promotionMarshaller in injected in acesFormFactory as a constructor arg in aces-beans.xml. And the definition of promotionMarshaller is there in ApplicationContext.xml of webapp-control which is there in the dependency list of pom.xml of the current component.
<dependency>
<groupId>webapp</groupId>
<artifactId>webapp-control</artifactId>
</dependency>
<dependency>
<groupId>webapp</groupId>
<artifactId>webapp-control</artifactId>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
I don't get why the parent application context is not getting loaded while running the Junit Test case. Please look into this as I am stuck here for 2 days now.
Here's a snippet from aces-beans.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="acesFormFactory"
class="com.company.impl.AcesFormFactoryImpl">
<constructor-arg ref="checkoutPromotionMarshaller" />
</bean>
My environment is Spring 3.2.1, Junit 4, JDK 1.7, Maven 3.0.4

Resources