AnnotationConfigRegistry not found in spring 4 - spring

I am having an strange behavior, using spring 4.1.1 I get this error.
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project newvalia-view: Compilation failure
[ERROR] /C:/Users/edu/IdeaProjects/newvalia/newvalia- view/src/main/java/com/newvalia/web/init/WebInitContext.java:[19,12] cannot access org.springframework.context.annotation.AnnotationConfigRegistry
[ERROR] class file for org.springframework.context.annotation.AnnotationConfigRegistry not found
while if I downgrade to spring 4.0.7 it compiles correctly.
I am using simple spring webmwc configuration :
#Configuration
#ComponentScan(value = "com.newvalia.web")
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
}
public class WebInitContext implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebMvcConfig.class);
ctx.setServletContext(container);
Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
is this a new expected behavior?

import org.springframework.context jar correctly in your pom file , and thats it .
Hope that Helps .

Add spring context dependency :
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>

Related

Spring server doesn't start with actuator dependency

If I add spring boot actuator dependency my server doesn't start. I get the following error:
SEVERE [main] org.apache.catalina.startup.HostConfig.deployDescriptor Error deploying deployment descriptor [tomcat path\conf\Catalina\localhost\test.xml]
java.lang.IllegalStateException: Error starting child
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:720)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:690)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:692)
...
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/agromarket]]
at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:717)
... 37 more
Caused by: java.lang.ClassCastException: org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext
at rs.navigator.alexandar.sync.WebAppInitializer.onStartup(WebAppInitializer.java:34)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:174)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5161)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
Dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Any ideas why? From my knowledge even if the versions aren't compatible the server should still be able to start.
Edit:
My WebAppInitializer:
public class WebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
System.out.println(("------------------ Sync context initialized and application started ------------------"));
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
// ctx.register(ServletContextListener.class);
// ctx.register(SecurityConfiguration.class);
// ctx.register(SpringFoxConfig.class);
// ctx.register(WebMvcConfigure.class);
// ctx.register(JPAConfiguration.class);
// ctx.setServletContext(servletContext);
// Reconfigure log4j
// ServletContext sctx = ctx.getServletContext();
System.setProperty("logFilename", servletContext.getContextPath().substring(1));
org.apache.logging.log4j.core.LoggerContext sctxLog =
(org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
sctxLog.reconfigure();
//Dispatcher servlet
ServletRegistration.Dynamic servlet = servletContext.addServlet("mvc-dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
ctx.close();
}
}
Error stack after adding #EnableAutoConfiguration
If you want benefit from the automatic features of Spring Boot, your #Configuration class must be annotated with #EnableAutoConfiguration.
Since the auto-configuration already creates a DispatcherServlet bound to /, you can safely change your WebAppInitializer class to:
#SpringBootApplication
public class WebAppInitializer extends SpringBootServletInitializer {
}

SpringBoot Fails now when I switch from spring data neo4j 4.1.3 to 5.0.0

Background
I have an application with spring data neo4j, and I switched from 4.1.3 to 5.0.0.
I believe that I have made all the necessary changes to convert my code over but I still get errors.
My current version of spring boot is
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
Problem
When I run: mvn spring-boot:run in the command line,
I get an error:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field actionRepository in myproject.service.ActionServiceImpl required a bean of type 'myproject.repository.ActionRepository' that could not be found.
Action:
Consider defining a bean of type 'myproject.repository.ActionRepository' in your configuration
My myproject.Application.java is currently
#SpringBootApplication
#EnableTransactionManagement
#EnableSwagger2
#EntityScan(basePackages = "myproject.domain")
public class Application {
public static void main(String[] args) {
new SpringApplication(Application.class).run(args);
}
#Bean
public Docket Api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.pathMapping("/")
.apiInfo(apiInfo());
}
private springfox.documentation.service.ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Service API")
}
}
And this does not find any of my controllers like myproject.controller.ActionController.java which contains
...
#RestController
#Api(value = "Action", description = "Actions Management API")
#RequestMapping(value = "/api/action")
public class ActionController extends Controller<Action> {
...
Attempt #1
If I add the annotation #ComponentScan({"myproject.request"}) to my Application class, the error goes away, but spring boot cannot load any controllers and as such my Swagger shows no APIs and no controllers are run. This is not the solution. #SpringBootApplication should take care of all this.
Question
How do I reconfig spring boot to start working like it did in version 4.1.3 of spring data neo4j?
UPDATE 1 ATTEMPT #2
I tried adding this annotation to my class Application
#EnableNeo4jRepositories("myproject.repository")
And the error changed to something less clean:
...
2017-10-05 13:19:46.992 ERROR 561 --- [ main] o.s.boot.SpringApplication : Application startup failed
java.lang.NoSuchMethodError: org.springframework.data.repository.config.RepositoryConfigurationSource.getAttribute(Ljava/lang/String;)Ljava/util/Optional;
at org.springframework.data.neo4j.repository.config.Neo4jRepositoryConfigurationExtension.postProcess(Neo4jRepositoryConfigurationExtension.java:110) ~[spring-data-neo4j-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.data.repository.config.RepositoryConfigurationDelegate.registerRepositoriesIn(RepositoryConfigurationDelegate.java:130) ~[spring-data-commons-1.12.0.RELEASE.jar:na]
at org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport.registerBeanDefinitions(RepositoryBeanDefinitionRegistrarSupport.java:83) ~[spring-data-commons-1.12.0.RELEASE.jar:na]
...
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.4.1.RELEASE:run (default-cli) on project myproject: An exception occurred while running. null: InvocationTargetException: org.springframework.data.repository.config.RepositoryConfigurationSource.getAttribute(Ljava/lang/String;)Ljava/util/Optional; -> [Help 1]
[ERROR]
...
UPDATE 2
In an attempt to use the #EnableNeo4jRepositories("myproject.repository") and bypass the error in Update 1, I tried:
mvn clean install spring-boot:repackage
And it gave a Build Success, but the same error persists:
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.4.1.RELEASE:run (default-cli) on project myproject: An exception occurred while running. null: InvocationTargetException: org.springframework.data.repository.config.RepositoryConfigurationSource.getAttribute(Ljava/lang/String;)Ljava/util/Optional; -
UPDATE 3
I have the new annotation and changed my pom from:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>1.12.0.RELEASE</version>
</dependency>
to
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
and now mvn spring-boot:run
gives the error:
***************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean named 'getSessionFactory' that could not be found.
Action:
Consider defining a bean named 'getSessionFactory' in your configuration.
Try adding this annotation on your configuration class :
#EnableNeo4jRepositories("myproject.repository")
Update :
I just saw you're on Spring boot 1.4. SDN 5 is only compatible with Spring Boot 2.0.
Details are in the compatibility table.

Spring property placeholders in application-context.xml inside dependency jar

For my spring boot application I use annotation based configuration and a WebApplicationInitalizer.
One of my dependencies provides a spring configuration in an xml, included in the jar. I use #ImportResource to load the context xml. This seems to work, except for the fact that inside this xml, there are property placeholders, for example ${poolsize:10}
Apparently, spring does not automatically replace these placeholders (I get a NumberFormatException). Is there some extra configuration I need to add?
Our startup class:
public class Application implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) throws ServletException {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
// config
rootContext.register(JmsConfiguration.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
}
}
And the configuration class (we use spring-jms):
#Configuration
#EnableJms
#ComponentScan(basePackages = { "..." })
public class JmsConfiguration implements JmsListenerConfigurer {
// config for jms listener and jaxb, nothing to do with property handling
}
Perhaps I'm mistaken in thinking that using a WebapplicationInitializer is how to use spring boot. Perhaps we don't even need spring boot? The only spring boot related dependency we use is:
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.3.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
Spring dependencies we use:
org.springframework:spring-context:jar:4.3.8.RELEASE:compile
org.springframework:spring-jms:jar:4.3.8.RELEASE:compile
org.springframework:spring-oxm:jar:4.3.8.RELEASE:compile
org.springframework:spring-context:jar:4.3.8.RELEASE:compile
org.springframework:spring-beans:jar:4.3.8.RELEASE:compile
I figured it out thanks #M. Deinum
We don't need spring boot to use the WebApplicationInitializer, but (at least without spring boot) we have to declare our own PropertySourcesPlaceholderConfigurer:
#Configuration
#ImportResource(locations = {"classpath*:/library-context.xml"})
public class MyConfiguration {
#Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
NB. This works out of the box in spring boot thanks to #EnableAutoConfiguration and #PropertyPlaceholderAutoConfiguration which contains the exact same PropertySourcesPlaceholderConfigurer bean

Spring Boot soap + hibernate configuration

I have already a soap ws working with spring boot.
My doubt now its how to add in WebAppInitializer file the injection of Hibernate.
My file its like this now
public class WebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
ctx.setServletContext(servletContext);
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(ctx);
servlet.setTransformWsdlLocations(true);
Dynamic dynamic = servletContext.addServlet("dispatcher",servlet);
dynamic.addMapping("/soapws/*");
dynamic.setLoadOnStartup(1);
}
}
How to add the hibernate configuration/injection?
You can use the spring boot starter jpa. Include the below dependency in your pom.xml (if using maven).
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
And then, specify hibernate options in application.properties. For example,
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
etc
Spring Boot tries to guess the location of your #Entity definitions, based on the #EnableAutoConfiguration it finds. To get more control, you can use the #EntityScan annotation
Refer to this for more details :
http://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html

Fongo - OperationExecutor not found

I would like to use fongo 2.0.x in my Spring boot application, but I getting errror
Error:(23, 44) java: cannot access com.mongodb.operation.OperationExecutor
class file for com.mongodb.operation.OperationExecutor not found
Here is my AbstractMongoConfiguration
#Configuration
#ComponentScan("com.foo")
public class MongoDbConfig extends AbstractMongoConfiguration {
#Override
protected String getDatabaseName() {
return "demo";
}
#Override
public Mongo mongo() throws Exception {
return new Fongo(getDatabaseName()).getMongo(); //this line throws the error
}
}
From the Fongo documentation:
It has a "provided" dependency on the mongo-java-driver and was tested with 2.13.0 and 3.0.1.
So Fongo wants mongo-java-driver on the classpath, and I'm guessing you don't have it (or at least not in the test scope).
So make sure the following is in your build script:
For Maven:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.1</version>
<scope>test</scope>
</dependency>
For Gradle:
testCompile 'org.mongodb:mongo-java-driver:3.4.1'

Resources