Spring - <constructor-arg> - java.lang.IncompatibleClassChangeError - spring

Hi I use EclipseEE and Java8_40. I start with the Spring Framework and have some problem. When I want use constructor in beans.xml the program create a Exception.
I have in CLASSPATH :
- commons-logging-1.2.jar
- commons-logging-1.2-javadoc.jar
and Spring *.jars
- spring-aop-4.1.5.RELEASE.jar
- spring-asm-3.1.1.RELEASE.jar
- spring-beans-4.1.5.RELEASE.jar
- spring-context-4.1.5.RELEASE.jar
- spring-aspects-4.1.5.RELEASE.jar
- spring-context-support-4.1.5.RELEASE.jar
- spring-core-4.1.5.RELEASE.jar
- spring-web-4.1.5.RELEASE.jar
- spring-webmvc-4.1.5.RELEASE.jar
- spring-expression-4.1.5.RELEASE.jar
SPRING BEAN
package beans;
public class SequenceGenerator {
private String prefix;
private String suffix;
private int initial;
private int counter;
public SequenceGenerator() {}
public SequenceGenerator(String prefix, String suffix, int initial) {
this.prefix = prefix;
this.suffix = suffix;
this.initial = initial; }
public void setPrefix(String prefix) {
this.prefix = prefix; }
public void setSuffix(String suffix) {
this.suffix = suffix; }
public void setInitial(int initial) {
this.initial = initial; }
public synchronized String getSequence() {
StringBuffer buffer = new StringBuffer();
buffer.append(prefix);
buffer.append(initial + counter++);
buffer.append(suffix);
return buffer.toString(); }
}
CLIENT
package klient.program;
import org.springframework.context.*;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.SequenceGenerator;
public class Program {
#SuppressWarnings("resource")
public static void main(String [] args){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
SequenceGenerator generator = (SequenceGenerator) context.getBean("sequenceGenerator");
System.out.println(generator.getSequence());
System.out.println(generator.getSequence());
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<bean name="sequenceGenerator" class="beans.SequenceGenerator">
<constructor-arg><value>30</value></constructor-arg>
<constructor-arg><value>A</value></constructor-arg>
<constructor-arg><value>100000</value></constructor-arg>
</bean>
</beans>
Exception :
Exception in thread "main" java.lang.IncompatibleClassChangeError: class org.springframework.core.LocalVariableTableParameterNameDiscoverer$ParameterNameDiscoveringVisitor has interface org.springframework.asm.ClassVisitor as super class
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.springframework.core.LocalVariableTableParameterNameDiscoverer.inspectClass(LocalVariableTableParameterNameDiscoverer.java:114)
at org.springframework.core.LocalVariableTableParameterNameDiscoverer.getParameterNames(LocalVariableTableParameterNameDiscoverer.java:87)
at org.springframework.core.PrioritizedParameterNameDiscoverer.getParameterNames(PrioritizedParameterNameDiscoverer.java:65)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:182)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1131)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1034)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at klient.program.Program.main(Program.java:8)

You don't need spring-asm-(version).jar.
This dependency was in spring-core earlier:
Note however that we’ve eliminated the dedicated spring-asm jar in M2
in favor of including org.springframework.asm classes directly in
spring-core. Both of these upgrades are good news for JDK7 users
writing Spring components in dynamic JVM languages, as these new
versions of CGLIB and ASM properly handle the new invokedynamic
bytecode instruction introduced in JDK7.
http://spring.io/blog/2012/09/12/spring-framework-3-2-m2-released
How wrote here: https://github.com/spring-projects/spring-framework/commit/c16f18a5fd659f34d6290b5f2cffe54534b7592a this module full removed, instead use ASM 4

Related

spring security messaging throws NullPointerException internally (Spring context is null!)

this is websocket security config:
#Configuration
public class WSSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer implements ApplicationContextAware {
#Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages
.nullDestMatcher().denyAll()
.simpSubscribeDestMatchers("/topic/t01", "/topic/t99").authenticated()
.anyMessage().denyAll();
}
}
the context fails to load with this error (trimmed only to the relevant parts):
Caused by: java.lang.NullPointerException: null
at org.springframework.security.config.annotation.web.socket.AbstractSecurityWebSocketMessageBrokerConfigurer.configureClientInboundChannel(AbstractSecurityWebSocketMessageBrokerConfigurer.java:106) ~[spring-security-config-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.web.socket.config.annotation.DelegatingWebSocketMessageBrokerConfiguration.configureClientInboundChannel(DelegatingWebSocketMessageBrokerConfiguration.java:73) ~[spring-websocket-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.messaging.simp.config.AbstractMessageBrokerConfiguration.getClientInboundChannelRegistration(AbstractMessageBrokerConfiguration.java:153) ~[spring-messaging-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.messaging.simp.config.AbstractMessageBrokerConfiguration.clientInboundChannelExecutor(AbstractMessageBrokerConfiguration.java:144) ~[spring-messaging-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.socket.config.annotation.DelegatingWebSocketMessageBrokerConfiguration$$EnhancerBySpringCGLIB$$e1380a16.CGLIB$clientInboundChannelExecutor$35(<generated>) ~[spring-websocket-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.socket.config.annotation.DelegatingWebSocketMessageBrokerConfiguration$$EnhancerBySpringCGLIB$$e1380a16$$FastClassBySpringCGLIB$$1a42e7b2.invoke(<generated>) ~[spring-websocket-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.socket.config.annotation.DelegatingWebSocketMessageBrokerConfiguration$$EnhancerBySpringCGLIB$$e1380a16.clientInboundChannelExecutor(<generated>) ~[spring-websocket-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_342]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_342]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_342]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_342]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
... 93 common frames omitted
I looked at the culprit class AbstractSecurityWebSocketMessageBrokerConfigurer, the exception was thrown in method configureClientInboundChannel, the context is null. after some debugging I found out that the context was set before this method get called (of course with not null value) by setApplicationContext but the object (proxy) reference was not same when these two method was called (configureClientInboundChannel and setApplicationContext)
#Override
public final void configureClientInboundChannel(ChannelRegistration registration) {
ChannelSecurityInterceptor inboundChannelSecurity = context.getBean(ChannelSecurityInterceptor.class);
.
.
.
}
more information:
spring boot version: 2.3.1.RELEASE
spring security version: 5.3.3.RELEASE

Spring data cassandra - Cannot find changelog location: class path resource

I am integrating cassandra in my application and i have no clue of this exception ! i did not find any help online so posting a question here.
I followed this link
Cassandra config
#Configuration
#PropertySource(value = {"classpath:cassandra.properties"})
#EnableCassandraRepositories(basePackages = { "com.demo" })
public class CassandraConfig {
#Autowired
private Environment environment;
#Bean
public CassandraClusterFactoryBean cluster() {
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints(environment.getProperty("cassandra.contactpoints"));
cluster.setPort(Integer.parseInt(environment.getProperty("cassandra.port")));
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(environment.getProperty("cassandra.keyspace"));
session.setConverter(converter());
session.setSchemaAction(SchemaAction.NONE);
return session;
}
#Bean
public CassandraOperations cassandraTemplate() throws Exception {
return new CassandraTemplate(session().getObject());
}
}
Maven pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-cassandra</artifactId>
</dependency>
...
cassandra.properties
cassandra.contactpoints=127.0.0.1
cassandra.port=9042
cassandra.keyspace=test
cassandra repository
public interface CustomerRepository extends CassandraRepository<Customer> {
}
casssandra entity class
#Table
public class Customer {
#PrimaryKeyColumn(name = "id",ordinal = 1,type = PrimaryKeyType.CLUSTERED)
private UUID id;
#PrimaryKeyColumn(name="user",ordinal = 0,type = PrimaryKeyType.PARTITIONED)
private String name;
private String address;
public Customer()
{
}
public Customer( UUID id, String name, String address )
{
this.id = id;
this.name = name;
this.address = address;
}
#Override
public String toString()
{
return String.format("Customer[id=%s, name='%s', address='%s']", this.id, this.name, this.address);
}
}
This is the error when i run the main class :
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration$LiquibaseConfiguration': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot find changelog location: class path resource [db/changelog/db.changelog-master.yaml] (please add changelog or check your Liquibase configuration)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:408)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1566)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:368)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
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)
Caused by: java.lang.IllegalStateException: Cannot find changelog location: class path resource [db/changelog/db.changelog-master.yaml] (please add changelog or check your Liquibase configuration)
at org.springframework.util.Assert.state(Assert.java:385)
at org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration$LiquibaseConfiguration.checkChangelogExists(LiquibaseAutoConfiguration.java:83)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:349)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:300)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:133)
... 28 more
Thanks in advance !

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.");
}
}

Jboss error on deployment bean

I'm trying to deploy a bean that uses #Interceptros annotation in Jboss.
According to documentation I've created beanRefContext.xml and here is Bean code
#Stateless
#LocalBean
#Interceptors(SpringBeanAutowiringInterceptor.class)
public class ClienteBean implements ClienteBeanLocal {
public ClienteBean() {
// TODO Auto-generated constructor stub
}
#Autowired
private IClienteDAO cliente;
#Override
public List<ClienteDTO> selectALL() throws Exception {
return cliente.selectALL();
}
}
I am deploying it inside an EAR. When I try to deploy in Jboss 6 I get the following error:
Caused by: java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy
at sun.reflect.annotation.AnnotationParser.parseClassArray(Unknown Source) [:1.7.0_09]
at sun.reflect.annotation.AnnotationParser.parseArray(Unknown Source) [:1.7.0_09]
at sun.reflect.annotation.AnnotationParser.parseMemberValue(Unknown Source) [:1.7.0_09]
at sun.reflect.annotation.AnnotationParser.parseAnnotation(Unknown Source) [:1.7.0_09]
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(Unknown Source) [:1.7.0_09]
at sun.reflect.annotation.AnnotationParser.parseAnnotations(Unknown Source) [:1.7.0_09]
at java.lang.Class.initAnnotationsIfNecessary(Unknown Source) [:1.7.0_09]
at java.lang.Class.getAnnotations(Unknown Source) [:1.7.0_09]
at org.jboss.reflect.plugins.introspection.IntrospectionTypeInfoFactoryImpl.readAnnotations(IntrospectionTypeInfoFactoryImpl.java:610) [jboss-reflect.jar:2.2.0.GA]
at org.jboss.reflect.plugins.introspection.IntrospectionTypeInfoFactoryImpl.getAnnotations(IntrospectionTypeInfoFactoryImpl.java:126) [jboss-reflect.jar:2.2.0.GA]
at org.jboss.reflect.plugins.InheritableAnnotationHolder.getDeclaredAnnotations(InheritableAnnotationHolder.java:96) [jboss-reflect.jar:2.2.0.GA]
at org.jboss.reflect.plugins.ClassInfoImpl.getAnnotations(ClassInfoImpl.java:181) [jboss-reflect.jar:2.2.0.GA]
at org.jboss.reflect.plugins.AbstractAnnotatedInfo.getUnderlyingAnnotations(AbstractAnnotatedInfo.java:63) [jboss-reflect.jar:2.2.0.GA]
at org.jboss.scanning.plugins.visitor.ClassHierarchyResourceVisitor.handleClass(ClassHierarchyResourceVisitor.java:76) [:1.0.0.GA]
at org.jboss.scanning.plugins.visitor.ReflectResourceVisitor.doVisit(ReflectResourceVisitor.java:108) [:1.0.0.GA]
at org.jboss.scanning.plugins.visitor.ReflectResourceVisitor.visit(ReflectResourceVisitor.java:86) [:1.0.0.GA]
... 53 more
How can I solve it?
Seems JBoss is not seeing SpringBeanAutowiringInterceptor.class. In your EAR file put your spring jars on the lib directory. See if that works.
If you are using maven to assemble your EAR file you can do something like this:
http://maven.apache.org/plugins/maven-ear-plugin/examples/customizing-module-location.html

How to mock SessionFactory or Session by PowerMockito in a project using Spring and Hibernate?

I am working on a project that uses Spring and Hibernate. I have an abstract DAO that contains SessionFactory. I need to mock SessionFactory or Session for my unit test. But I have not been successful so far. Below is the code. Anyone has any idea? Thank you.
Here is my AbstractDAO
public abstract class AbstractDAO {
protected JdbcTemplate jdbcTemplate;
protected SessionFactory sessionFactory;
protected NamedParameterJdbcTemplate namedParameterJdbcTemplate;
...
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}}
And here is my ConcreteDAO
public class LoginDAO extends AbstractDAO implements InitializingBean {
...
public User getLoggedinUserByUserid(Long userid){
log.info("in getLoggedinUserByUserid");
User result = null;
Session session = sessionFactory.openSession();
try {
session.beginTransaction();
result = (User) session.get(User.class, userid);
session.getTransaction().rollback();
session.close();
} catch (Exception e) {
log.error(e,e);
session.getTransaction().rollback();
session.close();
}
return result;
}
...}
and here is my test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "LoginDAOTest-context.xml" })
#PrepareForTest({SessionFactory.class, Session.class, Transaction.class})
public class LoginDAOTest2 extends BaseDAO {
private static final Logger log = Logger.getLogger(LoginDAOTest2.class);
#Rule
public PowerMockRule rule = new PowerMockRule();
private LoginDAO loginDAO = new LoginDAO();
private SessionFactory mockedSessionFactory;
private Session mockedSession;
private Transaction mockedTransaction;
#Autowired
public void setSessionFactory(SessionFactory sessionFactoryCore) {
mockedSessionFactory = PowerMockito.mock( sessionFactoryCore.getClass());
mockedSession = PowerMockito.mock(Session.class);
PowerMockito.doReturn(mockedSession).when(mockedSessionFactory).openSession();
PowerMockito.doReturn(mockedTransaction).when(mockedSession).beginTransaction();
loginDAO.setSessionFactory(this.mockedSessionFactory);
}
#Test
public void shouldRollbackInGetLoggedinUserByUseridWhenSessionThrowsException() {
// Given
PowerMockito.doThrow(new Exception()).when(mockedSession).get(User.class, 12L);
// When
loginDAO.getLoggedinUserByUserid(12L);
// Then
verify(mockedTransaction, times(1)).rollback();
}
}
and here is the result of junit.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.aeon.ps.dao.LoginDAOTest2': Injection of autowired dependencies failed; nested exception is java.lang.NoClassDefFoundError: org/mockito/internal/MockitoInvocationHandler
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.NoClassDefFoundError: org/mockito/internal/MockitoInvocationHandler
at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:138)
at com.aeon.ps.dao.LoginDAOTest2.setSessionFactory(LoginDAOTest2.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 26 more
Caused by: java.lang.ClassNotFoundException: org.mockito.internal.MockitoInvocationHandler
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 35 more
Why don't do this :
#Before
public void setUp() {
mockedSessionFactory = Mockito.mock(SessionFactory.class);
mockedSession = Mockito.mock(Session.class);
mockedTransaction = Mockito.mock(Transaction.class);
Mockito.when(mockedSessionFactory.openSession()).thenReturn(mockedSession);
Mockito.when(mockedSession.beginTransaction()).thenReturn(mockedTransaction);
loginDAO.setSessionFactory(this.mockedSessionFactory);
}
instead of :
#Autowired
public void setSessionFactory(SessionFactory sessionFactoryCore) {
mockedSessionFactory = PowerMockito.mock( sessionFactoryCore.getClass());
mockedSession = PowerMockito.mock(Session.class);
PowerMockito.doReturn(mockedSession).when(mockedSessionFactory).openSession();
PowerMockito.doReturn(mockedTransaction).when(mockedSession).beginTransaction();
loginDAO.setSessionFactory(this.mockedSessionFactory);
}
In addition, it allows you to not use powermock.
Interesting part is here :
Caused by: java.lang.NoClassDefFoundError: org/mockito/internal/MockitoInvocationHandler
at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:138)
at com.aeon.ps.dao.LoginDAOTest2.setSessionFactory(LoginDAOTest2.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 26 more
It means that powermock is using an internal class that is not available in the mockito distribution your are using.
From that information I gather you are using Mockito 1.9.5-rc1, with some other recent Powermock release. As of now, Johan din't released a newer version of Powermock that take care of the changes that were made in Mockito 1.9.5-rc1.
These refactoring changes in Mockito were made to help the introduction of the MockMaker API, which allows a third party to provide his own mock factory, bytecode engine or else to create mocks.
See the documentation here : http://docs.mockito.googlecode.com/hg/1.9.5-rc1/org/mockito/Mockito.html
So for now, you should use Mockito 1.9.0 if you are using Powermock.

Resources