Spring Boot: class in package not being loaded - java

I'm having trouble with a Spring Boot app that is not loading a config class with 2 beans in it. The weird thing is that another config class in the same package gets loaded.
Both config classes have #Configuration in them. The one that doesn't load also has a #ComponentScan(basePackages = {"com.example.package.in.jar"}) in it.
The base packages value refers to a package in a loaded jar file.
I'm using Gradle 3.4.1, Spring Boot 1.5.3. When I turn on Spring debugging, it shows the other config class being found and loaded, but it just skips over the other one. No exceptions are thrown - no errors at all.
It would be one thing if the code didn't run, but at least load the class or throw an error, but the log file that was created showed no errors.

Use #EntityScan("com.yourpackage*") will check all the packages starts with "com.yourpackage"
Refer https://github.com/Roshanmutha/JPARepo_44149690/blob/master/src/main/java/com/rcmutha/usl/controller/Application.java

So it turns out that the problem was that it the file wasn't even being seen, period. After attempting the suggestions, I found another option to try: #ImportAutoConfiguration. I used this annotation in the main Spring Boot app file and specified the files in my config package. This is when the compiler said that it couldn't resolve the file I was having problems with.
I cut out the contents, deleted the file and re-created it with a slightly different name, pasted back the contents and update the file list for the annotation. It worked!
The file showed up in the file tree in IntelliJ, but it wasn't being seen by the compiler, so it wasn't being configured. Within the annotation it had to look for it explicitly, and then the error was produced.
Thank you to those that posted suggestions.
Les

Related

Spring Web App Configuration doesn't take enviroment variables

I started setting tests for my project. It taked a while to settup the context. Now that I have achived it, I am getting trouble to make the tests work on multiple enviroments.
I set up the application test with these anotations:
#ContextConfiguration({"/applicationContext-test.xml", "/appServlet/servlet-context.xml"})
#WebAppConfiguration
#RunWith(SpringJUnit4ClassRunner.class)
#AutoConfigureMockMvc
public class ControllerUserTest {}
The trouble comes from the config file. When running the project on enviroments a parent config file values get replaced by environment ones. For testing for some reason I don't find a way to reproduce this. Meanwhile I setted up the parent config file with develop variables. To resolve this, the parent file was restored and using anotations like #TestPropertySource(properties="env=pre") or #ActiveProfiles("pre"). Neither way the parent file variables are replaced by environment ones. This kind of annotationa allows to change profile from class but It would be intereset to change the envoroment it from command line.
I also tried to use #BeforeClass annotation but the context annotations are executed before it.
To add more info about how the config is read. On "/appServlet/servlet-context.xml" I have a component-scan that points to a package where ApplicationConfig.java is stored . This config has this anotations #Configuration #PropertySource(value = { "classpath:nsf.properties" }).
In which direction I have to investigate to achieve my goal? Thanks in advance

How does Java runtime find my main class?

I am learning Spring Boot. I made a simple Spring Boot project that can output a hello world string at http://localhost:8080/welcome
I use Maven to build my project that would output a jar file.
To start up my spring boot app, I use the command as below
java -jar my-springboot-app.jar
My question is:
How is java smart enough to locate my main class and its main method (e.g. the application launcher)?
I checked the jar file and browsed those BOOT-INF & META-INF and could not find any clues.
Does the spring boot framework (#SpringBootApplication) or maven automatically do the magic for me?
In case of spring boot jar the things are little bit more complicated than regular jar. Mainly because spring boot applicaton jar is not really a JAR (by jar I mean something that has manifest and compiled classes). Regular JARs can be "recognized" and processed by jvm, however in Spring Boot there are also packed dependencies (take a look at BOOT-INF/lib) so its jars inside JARs. How to read this?
It turns out that spring boot always has its own main class that is indeed referred to in MANIFEST.MF and this a real entry point of the packaged application.
The manifest file contains the following lines:
Main-Class: org.springframework.boot.loader.JarLauncher
Start-Class: com.example.demo.DemoApplication
Main-Class is a JVM entry point. This class, written by spring developers, basically does two things:
- Establishes a special class loader to deal with a "non-regular-jar" nature of spring boot application. Due to this special class loaders spring boot application that contains "jars" in BOOT-INF/lib can be processed, for example, regular java class loaders apparently cannot do this.
- Calls the main method of Start-Class value. The Start-Class is a something unique to spring boot applications and it denotes the class that contains a "main" method - the class you write and the class you think is an entry point :) But from the point of view of the spring boot infrastructure its just a class that has an "ordinary" main method - a method that can be called by reflection.
Now regarding the question "who builds the manifest":
This MANIFEST.MF is usually created automatically by plugins offered by Spring Developers for build systems like Maven or Gradle.
For example, the plugin looks like this:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
During its work, this plugin identifies your main class (com.example.demo.DemoApplication in my example). This class is marked with #SpringBootApplication annotation and has a public static void main method.
However, if you put many classes like this the plugin probably won't recognize the correct class so you'll need to configure the plugin properties in POM.xml to specify the right class.
Java classes are executed within a larger context,
you run java -jar somejar.jar the class in question will be selected in the .jar file's manifest.
#SpringBootApplication will have componentscan, enabling auto configuration(autowired)
componentscan - to identify all the controller, service and configuration classes within the package.

Spring boot configuration in a multi-Module maven project

I'm having a problem properly setting up spring boot for my multi-module maven project.
There is a module "api" that uses another module "core". Api has an application.properties file that contains spring.mail.host=xxx. According to the spring boot documentation this provides you with a default implementation of the JavaMailSender interface, ready to be autowired.
However the class that is responsible for sending out the e-mails resides in the "core" package. When I try to build that module the build fails because no implementation of JavaMailSender can be found.
My guess then was that the mailing config should reside in "core" in a separate application.properties. I created that and moved the spring.mail.host property from the "api" to the "core" property file.
This time the core module builds successfully, but "api" fails to build because of the same exception, so I think I just moved the problem.
I don't understand the required structure for handling this type of situations well enough so I was wondering what the correct way is for having a "core" module containing all the correct configuration for sending mails and having other modules use the mailing code and config that resides in it.
I found the answer in another stack overflow question: How to add multiple application.properties files in spring-boot?
It turns out there can only be 1 application.properties file in the final jar that spring boot creates. To have multiple files you have to rename one of the files to something custom. I named the properties of the core module "core-application.properties".
Then in the API module I added this to the spring boot application class:
#SpringBootApplication
#PropertySource(value = {"core-application.properties", "application.properties"})
Doing this I can correctly use the base properties file and overwrite them in the more specific modules. Also you can still create profile-specific properties file (core-application-production.properties) with this setup, no need to add those to the propertysource manually). Note that #PropertySource does not work for yaml configuration files at this moment.
there is one effective application.properties per project. you just keep 2 properties file for a success build.
when api module use core module, the application.properties in core module is overwrite by api.
Your API's pom.xml must has dependency of CORE module.
the solution is to define properties files as a value of #PropertiesSource in Starter class.
but it is beter to put "classpath:" behind the properties files.
for example in Intellij idea after adding the "classpatch:" word berhind the files name, values become to link. like this:
#SpringBootApplication
#PropertySource(value = {"classpath:core-application.properties", "classpath:application.properties"})
I hope to helped you.

Annotation-specified bean name conflicts with existing, non-compatible bean definition

I'm using Spring 2.5.4 and am creating a Java application that I'm deploying onto Weblogic.
I have a class in an external library (which included in the WEB-INF/classes directory of the resulting WAR file of my application) that I want to use in my code. I've created an instance variable for an object of the class in my code and added the #Autowired annotation and a getter and setter. In my application context file I have declared a bean of the library class' type and added the following:
<context:annotation-config />
<context:component-scan base-package="com.mycompany" />
... in order to register an AutowiredAnnotationBeanPostProcessor that will scan the classes and process the annotation.
When I try and deploy the application, I get the following error:
java.lang.IllegalStateException: Annotation-specified bean name 'myBean' for bean
class [com.mycompany.package.ClassName] conflicts with existing, non-compatible
bean definition of same name and class [com.mycompany.otherPackage.ClassName]
I think this is because there's a class in the library which has the same name as one in my application code (both class' package names start with "com.mycompany"). Nb. this is NOT the class that I have added, but a different one. Is there any way I can circumvent this problem without changing the name of the class in my application?
Thanks for any assistance.
Old question but throwing my 2c of bad experience with similar problem.
If you have 2 classes with same name, but in different packages was there a time when you had your other class referenced by the failing Spring context? If so, I'd recommend to clean the AS cached files (typically the place where the WAR is extracted), clean/rebuild your WAR and deploy again. Restarting the app server is also recommended.
I found that application servers and web containers alike (Weblogic, WAS, Jboss, Tomcat) tend to leave behind the old classes and when application is deployed those stale .class files are loaded in JVM via some old references, which most of the time messes up the Spring context loader.
Typical scenario is when you have renamed/moved a class from one package to another, or even kept the package name the same but moved it to another module (jar). In such cases cached (left over) files in the AS work directory can cause big headaches. Wiping out the work directory in your AS should resolve the issue outright.
You should use #qualifier to avoid this kind of conflict please refer section 3.9.3.
I fixed the problem by removing the autowiring completely and accessing the bean by explicitly creating a reference to it through the application context and the getBean() method.
This would better fit as a comment to #Pavel Lechev's answer, but I don't have enough rep to comment yet.
For other's finding this, here's what I did to solve this problem. I am using Wildfly 9.0.2.Final and, IntelliJ IDEA 2016.1.3 Build #IU-145.1617. These steps should presumably work with JBoss as well.
Stop Wildfly server.
Navigate to $WILDFLY_HOME/standalone/. Delete the three following folders: lib/, log/ and temp/.
In IntelliJ, Build > Build Artifacts > All Artifacts > Clean (or just the artifacts you are deploying).
In IntelliJ, Build > Rebuild Project
Restart Wildfly and redeploy your artifact(s).
These steps remedied my issue of duplicate bean names detected in the Spring context after refactoring a package name upstream from a couple of Controllers.

Importing Spring beans from other Maven modules inside a WAR?

I have a new web app that is packaged as a WAR as part of a multi-module Maven project. The applicationContext.xml for this WAR references beans that are imported from the "service" module, which in turn imports beans from the "dao" module. The import statement in applicationContext.xml looks like this:
<import resource="classpath*:service.xml" />
and the one inside the service.xml file looks like this:
<import resource="classpath*:dao.xml" />
Neither Spring STS, nor Eclipse show any warnings or errors in my bean files. I reference the imported beans all over the place. The Maven build works fine and the DAO integration tests all pass (they use the beans). I don't have any service integration tests yet.
But when I start up the WAR in Jetty I get an error:
Error creating bean with name 'securityService'
Cannot resolve reference to bean 'userDAO' while setting constructor argument
All of the imported bean XML files can be found inside their respective JAR files in the WEB-INF/lib directory. Indeed, the service bean that threw the error is itself defined inside the service.xml file inside the service module's JAR file.
Apparently the service module can't find the bean that it imported from the dao module. Obviously I don't understand something...seems like this should this Just Work?
I enabled DEBUG logging for 'org.springframework' in order to see if I could learn anything. What I found were messages to the effect that the DAO beans had been created, but there was also a message about them having no name or id.
I check the file, and they all did have an id. So what was it? I check the XML namespace and saw:
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"
and noticed it was old (I am using Spring 3.0.2) and changed it to:
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
Once I changed it, Spring instantly threw half a dozen errors regarding beans that were defined incorrectly (but never used apparently). Once I fixed those errors, everything Just Worked. I've since gone through the entire system checking Spring XML file namespace versions.
Thanks to all for the help. Can't believe I wasted a day on this stupidity!!
The difference between the classpath:thingy.xml and classpath*:thingy.xml notation is that the former uses the standard classpath mechanism to resolve one resource (using ClassLoader.getResource(name)), whereas the latter will use ClassLoader.getResources(name) to retrieve all matching resources on the classpath, a distinction that should be irrelevant in your situation as I guess there is only one dao.xml file on the class path.
I think your problem is different, you are missing a leading slash.
Use this for a single resource
<import resource="classpath:/dao.xml" />
and this for multiple resources
<import resource="classpath*:/dao.xml" />
See
Spring Reference: The classpath*
prefix
Sun JavaDocs: ClassLoader
It should be like
<import resource="classpath:service.xml"/>
Are you having multiple applicationContexts and possibly the parent context is referring to a bean defined in the child context?

Categories

Resources