Creating library using Spring boot and aspectj - spring-boot

I have created a library using spring boot and aspectj.
I have created a configuration class
#Configuration
#EnableAspectJAutoProxy
#ComponentScan(basePackages="com.x.y")
public class LoggerConfig {
}
A class for the annotation
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface EnableHttpLogging {
}
and a class for the aspect
#Aspect
#Component
public class LoggerAspect {
#Around("execution(* *(..)) && #annotation(EnableHttpLogging)")
public Object handleController(final ProceedingJoinPoint proceedingJoinPoint)
throws Throwable {
LOG.info("controller....before ");
return proceedingJoinPoint.proceed();
}
}
An error has occured after importing a class configuration "#Import(LoggerConfig.class)" into my application and trying to run it, i have the following error:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embeddedServletContainerCustomizerBeanPostProcessor': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error Type referred to is not an annotation type: EnableHttpLogging
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:240)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:697)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:526)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at com.olps.reassurance.cgoa.endpoint.manager.Application.main(Application.java:43)
Caused by: java.lang.IllegalArgumentException: error Type referred to is not an annotation type: EnableHttpLogging
at org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:301)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.buildPointcutExpression(AspectJExpressionPointcut.java:207)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.checkReadyToMatch(AspectJExpressionPointcut.java:193)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.getClassFilter(AspectJExpressionPointcut.java:170)
at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:220)
at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:279)
at org.springframework.aop.support.AopUtils.findAdvisorsThatCanApply(AopUtils.java:311)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findAdvisorsThatCanApply(AbstractAdvisorAutoProxyCreator.java:118)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:88)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:69)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:347)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:299)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:422)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
... 14 more

You need to modify the method signature of handleController and the parameter provided inside #annotation. The example shown below should work.
#Aspect
#Component
#Slf4j
public class LoggerAspect {
#Around("execution(* *(..)) && #annotation(annotation)")
public Object handleController(
final ProceedingJoinPoint proceedingJoinPoint,
EnableHttpLogging annotation)
throws Throwable {
LOG.info("controller....before ");
return proceedingJoinPoint.proceed();
}
}

Related

NoSuchBeanDefinitionException raised even though #Autowire and # repository # service are properly configured

My controller class:
#Controller
public class UsersController
{
#Autowired
TechRequestService techrequestservices;
#RequestMapping(value="/service_request", method=RequestMethod.POST)
public #ResponseBody Map<String,Object> SaveServiceRequest(#Valid Servicerequest servicerequest,BindingResult result){
Map<String,Object> map = new HashMap<String,Object>();
Object obj=new Object();
if(result.hasErrors())
{
for (Object object : result.getAllErrors()) {
if(object instanceof FieldError) {
FieldError fieldError = (FieldError) object;
obj= (fieldError.getDefaultMessage());
}
map.put("status","400");
map.put("message",obj);
return map;
}}
techrequestservices.save_servicerequest(servicerequest);
map.put("status","200");
map.put("message","Your record have been saved successfully");
return map;
}
}
My Service Implementation class:
#Service
public class TechRequestServiceImpl implements TechRequestService{
#Autowired
TechRequestServiceDao techrequestservicedao;
public boolean save_servicerequest(Servicerequest servicerequest) {
return techrequestservicedao.save_servicerequest(servicerequest);
}
public List<Servicerequest> list() {
// TODO Auto-generated method stub
return techrequestservicedao.list();
}
}
My DaoImpl Class:
#Repository
#Transactional
public class TechRequestServiceDaoImpl implements TechRequestService {
#Autowired
SessionFactory session;
#Override
public boolean save_servicerequest(Servicerequest servicerequest) {
// TODO Auto-generated method stub
session.getCurrentSession().saveOrUpdate(servicerequest);
return true;
}
#Override
public List<Servicerequest> list() {
return session.getCurrentSession().createQuery("from Search_type_case").list();
}
}
The request comes through ajax and the pojo variables are getting their values initialized properly as i confirmed it by placing a print statement in ever setter method of pojos. The full stack trace of the exception as follows:
SEVERE: Exception sending context initialized event to listener instance of class
[org.springframework.web.context.ContextLoaderListener]
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'usersController': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: com.servicesapi.TechRequestService
com.controllers.UsersController.techrequestservices; nested exception
is org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'techRequestServiceImpl': Injection of
autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: com.daoapi.TechRequestServiceDao
com.servicesimpl.TechRequestServiceImpl.techrequestservicedao; nested
exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [com.daoapi.TechRequestServiceDao] 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.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at
org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at
org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at
org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4792)
at
org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5256)
at
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1421)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1411)
at java.util.concurrent.FutureTask.run(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at
java.lang.Thread.run(Unknown Source)
Is your Component-Scan set correctly to scan packages inside a given path? Try setting the component-scan in the spring xml configuration to scan the relevant packages as follows:
<context:component-scan base-package="com.main"/>
where your dao, service and controller packages are located inside com.main. This will scan all files under com.main while checking for bean definations.
Both TechRequestServiceImpl and TechRequestServiceDaoImpl implements TechRequestService therefore there are two beans of type TechRequestService in the context, but none of type: TechRequestServiceDao.
To fix: TechRequestServiceDaoImpl should implement TechRequestServiceDao

Adding custom behavior to all repositories with annotations

I am trying to add custom behavior to all repositories in my spring boot application only with annotations. Official documentation deals with JPA and not for MongoDB.
I have not created any custom methods yet as I want to check whether the default is working fine.
My code is as follows:
src/main/java/com/test/shipper/database:
MongoConfig.java
src/main/java/com/test/shipper/modal:
Shipper.java
src/main/java/com/test/shipper/repository:
BaseRepositoryFactoryBean.java
BaseRepositoryImpl.java
BaseRepository.java
ShipperRepository.java
src/main/java/com/test/shipper/service:
ShipperService.java
ShipperService.java
public class ShipperService {
#Autowired
private ShipperRepository repository;
public Shipper createShipper(Shipper shipper){
repository.deleteAll();
Shipper shipper1 = new Shipper("123","shipper123");
repository.insert(shipper1);
Shipper shipper2 = new Shipper("234","shipper234");
repository.insert(shipper2);
System.out.println("Find All!!");
List shippers = repository.findAll();
for (Shipper car: shippers) {System.out.println(car);}
repository.delete(shipper2.getShipperId());
shippers = repository.findAll();
for (Shipper car: shippers) {
System.out.println(car);
}
return null;
}
}
MongoConfig.java
#Configuration
#EnableMongoRepositories(basePackages = "com.test.shipper",
repositoryFactoryBeanClass = com.test.shipper.repository.BaseRepositoryFactoryBean.class)
public class MongoConfig extends AbstractMongoConfiguration {
#Value("test")
private String dbName;
#Value("127.0.0.1")
private String host;
#Value("27017")
private int port;
#Override
protected String getDatabaseName() {
return dbName;
}
#Bean
#Override
public Mongo mongo() throws Exception {
return new MongoClient(host, port);
}
#Bean
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongo(), dbName);
}
}
BaseRepository.java
#NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable>
extends MongoRepository<T, ID>
{
}
BaseRepositoryImpl.java
#NoRepositoryBean
public class BaseRepositoryImpl
extends SimpleMongoRepository implements BaseRepository
{
private MongoOperations mongoOperations;
public BaseRepositoryImpl(MongoEntityInformation metadata,
MongoOperations mongoOperations) {
super(metadata, mongoOperations);
this.mongoOperations = mongoOperations;
}
}
BaseRepositoryFactoryBean.java
public class BaseRepositoryFactoryBean, T, I extends Serializable>
extends MongoRepositoryFactoryBean {
public BaseRepositoryFactoryBean(Class repositoryInterface) {
super(repositoryInterface);
}
#Override
protected RepositoryFactorySupport getFactoryInstance(
MongoOperations operations) {
return new BaseMongoRepositoryFactory( operations );
}
private static class BaseMongoRepositoryFactory
extends MongoRepositoryFactory {
private MongoOperations mongo;
public BaseMongoRepositoryFactory(MongoOperations mongoOperations) {
super(mongoOperations);
this.mongo = mongoOperations;
}
#SuppressWarnings("unchecked")
protected Object getTargetRepository(RepositoryMetadata metadata) {
TypeInformation information = ClassTypeInformation.from((Class)metadata.getDomainType());
MongoPersistentEntity pe = new BasicMongoPersistentEntity(information);
MongoEntityInformation mongometa =
new MappingMongoEntityInformation(pe);
return new BaseRepositoryImpl( mongometa, mongo);
}
protected Class getRepositoryBaseClass(RepositoryMetadata metadata) {
return BaseRepository.class;
}
}
}
ShipperRepository.java
#Repository
public interface ShipperRepository
extends BaseRepository{
}
Shipper.java
#Document(collection = "shipper")
public class Shipper{
#Id
private String shipperId;
private String shipperName;
public Shipper() {
}
public Shipper(String shipperId, String shipperName) {
this.shipperId = shipperId;
this.shipperName = shipperName;
}
public String getShipperId() {
return shipperId;
}
public void setShipperId(String shipperId) {
this.shipperId = shipperId;
}
public String getShipperName() {
return shipperName;
}
public void setShipperName(String shipperName) {
this.shipperName = shipperName;
}
}
When the application starts I am getting the following exception.
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-08-06 23:08:26.849 ERROR 12828 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'shipperService': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shipperRepository': Invocation of init method failed; nested exception is java.lang.IllegalStateException: No suitable constructor found on interface com.test.shipper.repository.BaseRepository to match the given arguments: [class org.springframework.data.mongodb.repository.support.MappingMongoEntityInformation, class org.springframework.data.mongodb.core.MongoTemplate]. Make sure you implement a constructor taking these
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.6.RELEASE.jar!/:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.6.RELEASE.jar!/:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.6.RELEASE.jar!/:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.6.RELEASE.jar!/:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.6.RELEASE.jar!/:1.5.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.6.RELEASE.jar!/:1.5.6.RELEASE]
at com.test.shipper.ShipperApplication.main(ShipperApplication.java:12) [classes!/:0.0.1-SNAPSHOT]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48) [shipper_microservice-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.loader.Launcher.launch(Launcher.java:87) [shipper_microservice-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.loader.Launcher.launch(Launcher.java:50) [shipper_microservice-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51) [shipper_microservice-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shipperRepository': Invocation of init method failed; nested exception is java.lang.IllegalStateException: No suitable constructor found on interface com.test.shipper.repository.BaseRepository to match the given arguments: [class org.springframework.data.mongodb.repository.support.MappingMongoEntityInformation, class org.springframework.data.mongodb.core.MongoTemplate]. Make sure you implement a constructor taking these
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
... 27 common frames omitted
Caused by: java.lang.IllegalStateException: No suitable constructor found on interface com.test.shipper.repository.BaseRepository to match the given arguments: [class org.springframework.data.mongodb.repository.support.MappingMongoEntityInformation, class org.springframework.data.mongodb.core.MongoTemplate]. Make sure you implement a constructor taking these
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getTargetRepositoryViaReflection(RepositoryFactorySupport.java:360) ~[spring-data-commons-1.13.6.RELEASE.jar!/:na]
at org.springframework.data.mongodb.repository.support.MongoRepositoryFactory.getTargetRepository(MongoRepositoryFactory.java:98) ~[spring-data-mongodb-1.10.6.RELEASE.jar!/:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:199) ~[spring-data-commons-1.13.6.RELEASE.jar!/:na]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277) ~[spring-data-commons-1.13.6.RELEASE.jar!/:na]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263) ~[spring-data-commons-1.13.6.RELEASE.jar!/:na]
at org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean.afterPropertiesSet(MongoRepositoryFactoryBean.java:117) ~[spring-data-mongodb-1.10.6.RELEASE.jar!/:na]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
... 37 common frames omitted
</code></pre>
What could be the issue?

Multiple CassandraTemplates in Repository

I am building a SpringBoot App using Spring-Data-Cassandra (1.5.RC1) and Cassandra 3.x
Now, this is my CassandraConfig class:
#Configuration
#PropertySource(value = { "classpath:META-INF/cassandra.properties" })
#EnableCassandraRepositories(basePackages = { "com.rg" })
public class CassandraConfig {
#Autowired
private Environment environment;
private static final Logger LOGGER = LoggerFactory.getLogger(CassandraConfig.class);
#Bean
public CassandraClusterFactoryBean XCluster() {
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints(environment.getProperty("cassandra.X.contactpoints"));
cluster.setPort(Integer.parseInt(environment.getProperty("cassandra.X.port")));
return cluster;
}
#Bean
public CassandraMappingContext XMappingContext() {
return new BasicCassandraMappingContext();
}
#Bean
public CassandraConverter XConverter() {
return new MappingCassandraConverter(XMappingContext());
}
#Bean
public CassandraSessionFactoryBean XSession() throws Exception {
CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();
session.setCluster(XCluster().getObject());
session.setKeyspaceName(environment.getProperty("cassandra.X.keyspace"));
session.setConverter(XConverter());
session.setSchemaAction(SchemaAction.NONE);
return session;
}
#Bean
public CassandraOperations XCassandraTemplate() throws Exception {
return new CassandraTemplate(XSession().getObject());
}
#Bean
public CassandraClusterFactoryBean orgCluster() {
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints(environment.getProperty("cassandra.org.contactpoints"));
cluster.setPort(Integer.parseInt(environment.getProperty("cassandra.org.port")));
return cluster;
}
#Bean
public CassandraMappingContext orgMappingContext() {
return new BasicCassandraMappingContext();
}
#Bean
public CassandraConverter orgConverter() {
return new MappingCassandraConverter(activityMappingContext());
}
#Bean
public CassandraSessionFactoryBean orgSession() throws Exception {
CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();
session.setCluster(activityCluster().getObject());
session.setKeyspaceName(environment.getProperty("cassandra.org.keyspace"));
session.setConverter(activityConverter());
session.setSchemaAction(SchemaAction.NONE);
return session;
}
#Bean
public CassandraOperations orgCassandraTemplate() throws Exception {
return new CassandraTemplate(orgSession().getObject());
}
}
This is my Repository:
public interface ActivityRepository extends CassandraRepository<Activity> {
#Query("SELECT * FROM activities2 WHERE actor_id=?0")
Iterable<Activity> findByActor_Id(String actor_Id);
// #Query("SELECT * FROM activities2 WHERE viewer_id='?0'")
// Iterable<Activity> findByApp_Id(String appId);
}
However, the app fails to load with the following error:
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'XController': Unsatisfied dependency expressed through field 'XService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'XService' defined in file [/Users/jarvis/Documents/workspace/XStreamLog/bin/com/rg/Xstream/service/XService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'XRepository': Cannot resolve reference to bean 'cassandraTemplate' while setting bean property 'cassandraTemplate'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'cassandraTemplate' available
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1225)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:552)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at com.rg.Xstream.Application.main(Application.java:16)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'XService' defined in file [/Users/jarvis/Documents/workspace/XStreamLog/bin/com/rg/Xstream/service/XService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'XRepository': Cannot resolve reference to bean 'cassandraTemplate' while setting bean property 'cassandraTemplate'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'cassandraTemplate' available
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1154)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1056)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1136)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1064)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 18 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'XRepository': Cannot resolve reference to bean 'cassandraTemplate' while setting bean property 'cassandraTemplate'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'cassandraTemplate' available
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1492)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1237)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:552)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1136)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1064)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
... 31 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'cassandraTemplate' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:685)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1199)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
... 45 more
I don't undersatnd how the cassandraTemplate in the previous version of the project was Autowired into the app without me explicitly stating so in the code. If I can understand that I can get rid of this error. Any leads ?
You can use the below code as example:
#Configuration
public class CassandraConfig {
#Bean
public CassandraClusterFactoryBean cluster() {
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints(cassandraContactPoints);
cluster.setPort(Integer.parseInt(cassandraPort));
return cluster;
}
#Bean
public CassandraMappingContext mappingContext() {
return new BasicCassandraMappingContext();
}
#Bean
public CassandraConverter converter() {
return new MappingCassandraConverter(mappingContext());
}
#Bean
public CassandraSessionFactoryBean session() throws Exception {
CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();
session.setCluster(cluster().getObject());
session.setKeyspaceName(cassandraKeyspace);
session.setConverter(converter());
session.setSchemaAction(SchemaAction.NONE);
return session;
}
#Bean
public CassandraOperations cassandraTemplate() throws Exception {
return new CassandraTemplate(session().getObject());
}
}

Error creating bean with name 'endpoint' in spring 4

I created a JAX-WS application with spring (4.2.4), spring boot (1.3.1) and apache cxf (3.1.4). While running the application in apache server 8, i am getting below error:
2015-12-24 16:15:35.767 INFO 3956 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'errorPageFilter' to: [/*]
2015-12-24 16:15:36.120 WARN 3956 --- [ost-startStop-1] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'endpoint' defined in com.pd.config.PDConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.xml.ws.Endpoint]: Factory method 'endpoint' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.pd.webService.response.model.ResponseModel com.pd.webService.Impl.ServiceInterfaceImpl.responseModel; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.pd.webService.response.model.ResponseModel] 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)}
2015-12-24 16:15:36.135 ERROR 3956 --- [ost-startStop-1] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'endpoint' defined in com.pd.config.PDConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.xml.ws.Endpoint]: Factory method 'endpoint' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.pd.webService.response.model.ResponseModel com.pd.webService.Impl.ServiceInterfaceImpl.responseModel; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.pd.webService.response.model.ResponseModel] 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.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:764) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:357) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:305) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.context.web.SpringBootServletInitializer.run(SpringBootServletInitializer.java:149) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.context.web.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:129) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.boot.context.web.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:85) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175) [spring-web-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5151) [catalina.jar:8.0.20]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:8.0.20]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) [catalina.jar:8.0.20]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399) [catalina.jar:8.0.20]
at java.util.concurrent.FutureTask.run(Unknown Source) [na:1.8.0_60]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_60]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_60]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_60]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.xml.ws.Endpoint]: Factory method 'endpoint' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.pd.webService.response.model.ResponseModel com.pd.webService.Impl.ServiceInterfaceImpl.responseModel; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.pd.webService.response.model.ResponseModel] 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.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
... 27 common frames omitted
Below given the configuration:
package com.pd;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
PDConfig:
package com.pd.config;
import javax.xml.ws.Endpoint;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.ws.config.annotation.EnableWs;
import com.pd.webService.ServiceInterface;
import com.pd.webService.Impl.ServiceInterfaceImpl;
#EnableWs
#Configuration
public class PDConfig extends SpringBootServletInitializer {
#Bean
public ServletRegistrationBean dispatcherServlet() {
CXFServlet cxfServlet = new CXFServlet();
return new ServletRegistrationBean(cxfServlet, "/service/*");
}
#Bean(name="cxf")
public SpringBus springBus() {
return new SpringBus();
}
#Bean
public ServiceInterface myService() {
return new ServiceInterfaceImpl();
}
#Bean
public Endpoint endpoint() {
EndpointImpl endpoint = new EndpointImpl(springBus(), myService());
endpoint.publish("/serviceinterface");
return endpoint;
}
#Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");
container.addErrorPages(error401Page, error404Page, error500Page);
}
};
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
PDInitializer:
package com.pd.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class PDInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { PDConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
cxf-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:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<jaxws:endpoint id="serviceinterface" implementor="com.pd.webService.Impl.ServiceInterfaceImpl"
wsdlLocation="wsdl/serviceinterfaceimpl.wsdl" address="/ServiceInterfaceImplPort">
<jaxws:features>
<bean class="org.apache.cxf.feature.LoggingFeature" />
</jaxws:features>
</jaxws:endpoint>
</beans>
My service implementation:
package com.pd.webService.Impl;
import javax.jws.WebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import com.pd.webService.ServiceInterface;
import com.pd.webService.request.model.UserModel;
import com.pd.webService.response.model.ResponseModel;
#Component
#WebService(endpointInterface="com.pd.webService.ServiceInterface")
public class ServiceInterfaceImpl extends SpringBeanAutowiringSupport implements ServiceInterface {
#Autowired
ResponseModel responseModel;
#Override
public ResponseModel getUserInfo(UserModel userModel) {
responseModel.setUserName(userModel.getUserName());
responseModel.setAge(25);
responseModel.setCompany("MINDTREE");
responseModel.setExperience("2.8 years");
return responseModel;
}
}
Response Model:
package com.pd.webService.response.model;
import org.springframework.stereotype.Component;
#Component
public class ResponseModel {
private String userName;
private int age;
private String company;
private String experience;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
}
Could you please help me with this. Thanks in advance.
In the myService bean you have autowired filed of type ResponseModel.
You have to declare a bean of that type.
Something like this:
#Bean
public ResponseModel responseModel() {
return new ResponseModel();
}
Looks like when you extend SpringBeanAutowiringSupport that bean gets loaded befor the other beans in the spring container. You don't need that - remove extends SpringBeanAutowiringSupport from class ServiceInterfaceImpl

Spring Data Rest incompatible with Spring Data Neo4J?

I'm trying to incorporate Spring Data Rest into an application that is using Spring Data Neo4J. I get the following exception on start when I include Spring Data Rest into my application:
18:41:10.632 [main] INFO o.h.tool.hbm2ddl.SchemaUpdate - HHH000232: Schema update complete
18:41:11.280 [main] WARN o.e.j.u.component.AbstractLifeCycle - FAILED org.springframework.boot.context.embedded.jetty.ServletContextInitializerConfiguration$Initializer#2521bcf2: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter': Injection of autowired dependencies failed; nested exception is ...
// very long stack trace here
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.neo4j.support.Neo4jTemplate]: Circular reference involving containing bean 'myApplication' - consider declaring the factory method as static for independence from its containing instance. Factory method 'neo4jTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'neo4jMappingContext': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 277 common frames omitted
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'neo4jMappingContext': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:347) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:285) ~[spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at io.travelnet.TravelNetApplication$$EnhancerBySpringCGLIB$$6dfc1a9a.mappingInfrastructure(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
at org.springframework.data.neo4j.config.Neo4jConfiguration.neo4jTemplate(Neo4jConfiguration.java:136) ~[spring-data-neo4j-3.3.1.RELEASE.jar:na]
at io.travelnet.TravelNetApplication$$EnhancerBySpringCGLIB$$6dfc1a9a.CGLIB$neo4jTemplate$83(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
at io.travelnet.TravelNetApplication$$EnhancerBySpringCGLIB$$6dfc1a9a$$FastClassBySpringCGLIB$$484acc9c.invoke(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309) ~[spring-context-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at io.travelnet.TravelNetApplication$$EnhancerBySpringCGLIB$$6dfc1a9a.neo4jTemplate(<generated>) ~[spring-core-4.1.6.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_71]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_71]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_71]
at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_71]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 278 common frames omitted
Here's my dependency list:
dependencies {
compile("org.springframework.boot:spring-boot-starter-batch")
compile("org.springframework.cloud:spring-cloud-starter-aws")
compile("org.springframework.cloud:spring-cloud-aws-autoconfigure")
compile("commons-io:commons-io:2.4")
compile("org.springframework.boot:spring-boot-starter-data-rest")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.data:spring-data-neo4j:3.3.1.RELEASE")
compile("org.springframework.data:spring-data-commons:1.10.1.RELEASE")
compile("com.graphaware.neo4j:timetree:2.1.7.28.20")
compile("com.graphaware.neo4j:common:2.1.7.28")
compile("org.codehaus.jackson:jackson-mapper-asl:1.9.13")
// these are needed to provide Neo4J web admin interface
compile("org.neo4j.app:neo4j-server:2.1.8")
compile("org.neo4j.app:neo4j-server:2.1.8:static-web")
runtime("com.sun.jersey:jersey-server:1.17.1")
runtime("com.sun.jersey:jersey-servlet:1.17.1")
compile("org.codehaus.groovy:groovy")
runtime("org.postgresql:postgresql:9.4-1201-jdbc41")
//providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
testCompile("org.springframework.boot:spring-boot-starter-test")
testCompile "org.spockframework:spock-core:0.7-groovy-2.0"
}
The application runs as expected if I comment out compile("org.springframework.boot:spring-boot-starter-data-rest").
Is there a version mismatch perhaps?
EDIT to add config of main class as requested by Michael:
#Configuration
#EnableAutoConfiguration
#EnableAsync
#EnableScheduling
#SpringBootApplication
#EnableNeo4jRepositories(basePackages = "com.me.graph")
#EnableJpaRepositories(basePackages = "com.me.model")
#EnableTransactionManagement
class MyApplication extends Neo4jConfiguration implements CommandLineRunner {
MyApplication() {
setBasePackage("com.me.graph.domain");
}
#Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory().newEmbeddedDatabase("graph/neo4j.db");
}
#Autowired
GraphDatabaseService db;
#Bean
public SingleTimeTree timeTree() {
return new SingleTimeTree(db)
}
#Autowired
LocalContainerEntityManagerFactoryBean entityManagerFactory;
#Override
#Bean(name = "transactionManager")
public PlatformTransactionManager neo4jTransactionManager(GraphDatabaseService db) throws Exception {
return new ChainedTransactionManager(new JpaTransactionManager(entityManagerFactory.getObject()),
new JtaTransactionManagerFactoryBean(graphDatabaseService()).getObject());
}
#Override
public void run(String... strings) throws Exception {
startNeo4jServer()
}
private static final Logger log = LoggerFactory.getLogger(MyApplication.class);
public void startNeo4jServer() {
// used for Neo4j browser
try {
WrappingNeoServerBootstrapper neoServerBootstrapper;
GraphDatabaseAPI api = (GraphDatabaseAPI) db;
ServerConfigurator config = new ServerConfigurator(api);
config.configuration()
.addProperty(Configurator.WEBSERVER_ADDRESS_PROPERTY_KEY, "127.0.0.1");
config.configuration()
.addProperty(Configurator.WEBSERVER_PORT_PROPERTY_KEY, "7474");
neoServerBootstrapper = new WrappingNeoServerBootstrapper(api, config);
neoServerBootstrapper.start();
} catch(Exception e) {
//handle appropriately
log.error("Exception when starting N4J")
}
// end of Neo4j browser config
}
static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(MyApplication.class, args);
log.info("MyApplication started.");
}
}

Resources