When I try to run Spring java annotation based configuration I get that exception trace
Sep 28, 2014 10:24:38 PM
org.springframework.context.support.AbstractApplicationContext
prepareRefresh INFO: Refreshing
org.springframework.context.annotation.AnnotationConfigApplicationContext#20ad9418:
startup date [Sun Sep 28 22:24:38 EET 2014]; root of context hierarchy
Exception in thread "main" java.lang.IllegalStateException: Cannot
load configuration class: com.learn.HelloWorldConfig at
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:378)
at
org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanFactory(ConfigurationClassPostProcessor.java:263)
at
org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:265)
at
org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:126)
at
org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:609)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at com.learn.MainApp.main(MainApp.java:9) Caused by:
org.springframework.cglib.core.CodeGenerationException:
java.lang.reflect.InvocationTargetException-->null at
org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:237)
at
org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at
org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
at
org.springframework.context.annotation.ConfigurationClassEnhancer.createClass(ConfigurationClassEnhancer.java:128)
at
org.springframework.context.annotation.ConfigurationClassEnhancer.enhance(ConfigurationClassEnhancer.java:100)
at
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:368)
... 6 more Caused by: java.lang.reflect.InvocationTargetException 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:483) at
org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:384)
at
org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:219)
... 11 more Caused by: java.lang.SecurityException: class
"com.learn.HelloWorldConfig$$EnhancerBySpringCGLIB$$3f39adab"'s signer
information does not match signer information of other classes in the
same package at
java.lang.ClassLoader.checkCerts(ClassLoader.java:895) at
java.lang.ClassLoader.preDefineClass(ClassLoader.java:665) at
java.lang.ClassLoader.defineClass(ClassLoader.java:758) ... 17 more
HelloWorld.java
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
HelloWorldConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class HelloWorldConfig {
#Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}
MainApp.java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainApp {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(HelloWorldConfig.class);
ctx.refresh();
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
ctx.close();
System.out.println("Test");
}
}
Why I get that exception ?
Related
I'm working on a java desktop app using spring boot and javaFx.
it's a crud app so I'm working with mysql database
I want the controllers to be both spring boot and javaFx controllers, and for that I used setControllerFactory().
here is my application
Application:
package com.gi.quizui;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
javafx.application.Application.launch(QuizApplication.class, args);
}
}
QuizApplication:
package com.gi.quizui;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ConfigurableApplicationContext;
public class QuizApplication extends Application {
private ConfigurableApplicationContext applicationContext;
#Override
public void init() {
applicationContext = new SpringApplicationBuilder(com.gi.quizui.Application.class).run();
}
#Override
public void start(Stage stage) {
applicationContext.publishEvent(new StageReadyEvent(stage));
}
#Override
public void stop() {
applicationContext.close();
Platform.exit();
}
class StageReadyEvent extends ApplicationEvent {
public StageReadyEvent(Stage stage) {
super(stage);
}
public ConfigurableApplicationContext getAppContext() {
return applicationContext;
}
public Stage getStage() {
return ((Stage) getSource());
}
}
}
and stage initializer:
package com.gi.quizui;
import com.gi.quizui.QuizApplication.StageReadyEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import java.io.IOException;
#Component
public class StageInitializer implements ApplicationListener<StageReadyEvent> {
#Value("classpath:fxml/quiz.fxml")
private Resource quizResource;
public StageInitializer(#Value("${spring.application.ui.title}") String applicationTitle) {
this.applicationTitle = applicationTitle;
}
private String applicationTitle;
#Override
public void onApplicationEvent(StageReadyEvent event) {
Stage stage = event.getStage();
ConfigurableApplicationContext springContext = event.getAppContext();
try {
FXMLLoader fxmlLoader = new FXMLLoader(quizResource.getURL());
fxmlLoader.setControllerFactory(springContext::getBean);
Parent parent = fxmlLoader.load();
stage.setScene(new Scene(parent, 800, 600));
stage.setTitle(applicationTitle);
stage.show();
} catch (IOException e) {
throw new RuntimeException();
}
}
}
I keep getting this error : (edit)
Exception in Application start method
2021-01-16 15:37:15.286 INFO 8652 --- [lication Thread] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-01-16 15:37:15.320 INFO 8652 --- [lication Thread] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-01-16 15:37:15.343 INFO 8652 --- [lication Thread] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: java.lang.RuntimeException: javafx.fxml.LoadException:
/C:/Users/FacilOrdi/IdeaProjects/quizManagement/target/classes/fxml/quiz.fxml:7
at com.gi.quizui.StageInitializer.onApplicationEvent(StageInitializer.java:40)
at com.gi.quizui.StageInitializer.onApplicationEvent(StageInitializer.java:16)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:426)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:383)
at com.gi.quizui.QuizApplication.start(QuizApplication.java:20)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
... 1 more
Caused by: javafx.fxml.LoadException:
/C:/Users/FacilOrdi/IdeaProjects/quizManagement/target/classes/fxml/quiz.fxml:7
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2625)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2603)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2435)
at com.gi.quizui.StageInitializer.onApplicationEvent(StageInitializer.java:35)
... 16 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.gi.controllers.QuizController' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1177)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:938)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:980)
at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:227)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:752)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2722)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2552)
... 19 more
controller:
package com.gi.controllers;
import org.springframework.stereotype.Component;
#Component
public class QuizController {
}
I don't understand why it is not working, I've found related questions but I don't get how it works. It would be very helpful if there are other alternatives to do this.
In order to be aware of classes which have annotations such as #Component, etc., Spring Boot needs to scan through part of the classpath at startup time. By default it will scan the package containing the class you pass to SpringApplicationBuilder (Application in your case) and all subpackages.
So with the way you have things set up, it will scan com.gi.quizui and all subpackages.
Your QuizController class is not in a sub-package of com.gi.quizui; it is in com.gi.controllers. Consequently it won't be found.
The recommendation in the Spring Boot documentation is actually to have the Application class in the highest-level package that contains classes or resources, which is likely com.gi in your case. If you move that class to that package, it should fix the issue.
Alternatively, you can override the default behavior using the #ComponentScan annotation:
package com.gi.quizui;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan ;
#SpringBootApplication
#ComponentScan(basePackages={"com.gi.quizui","com.gi.controllers"})
public class Application {
public static void main(String[] args) {
javafx.application.Application.launch(QuizApplication.class, args);
}
}
A typesafe alternative is to use the basePackageClasses parameter instead of basePackages:
package com.gi.quizui;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan ;
import com.gi.controllers.QuizController ;
#SpringBootApplication
#ComponentScan(basePackageClasses={Application.class, QuizController.class})
public class Application {
public static void main(String[] args) {
javafx.application.Application.launch(QuizApplication.class, args);
}
}
Without mapping fxml this code run perfectly and load fxml
if i map fxml getting exception
i try alot but unable to understand what is the problem.....
SpringFxmlLoader class method load() return statement not returning anything because of which i think exception occur
javafx.fxml.LoadException:/E:/aa/JavaFXwithSpringBoot/bin/test/spring/boot/LoginPage.fxml:15
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579) at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441) at
javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409) at
test.spring.boot.config.SpringFXMLLoader.load(SpringFXMLLoader.java:34)
at
test.spring.boot.config.StageManager.loadViewNodeHierarchy(StageManager.java:80)
at
test.spring.boot.config.StageManager.switchScene(StageManager.java:31)
at test.spring.boot.Main.displayInitialScene(Main.java:35) at
test.spring.boot.Main.start(Main.java:24) at
com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at
com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at
com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method) at
com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at
com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at
com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Unknown Source) Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'test.spring.boot.LoginPageController'
available at
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:353)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:340)
at
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1090)
at
javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:929)
at
javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971)
at
javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220)
at
javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707) at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527) ... 16 more
Exception in Application start method 2017-10-24 17:18:03.779 ERROR
6416 --- [lication Thread] test.spring.boot.config.StageManager :
Unable to load FXML view >> /test/spring/boot/LoginPage.fxml
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'test.spring.boot.LoginPageController'
available at
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:353)
~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE] at
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:340)
~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1090)
~[spring-context-4.3.11.RELEASE.jar:4.3.11.RELEASE] at
javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:929)
~[jfxrt.jar:na] at
javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971)
~[jfxrt.jar:na] at
javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220)
~[jfxrt.jar:na] at
javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744)
~[jfxrt.jar:na] at
javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
~[jfxrt.jar:na] at
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527) ~[jfxrt.jar:na]
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
~[jfxrt.jar:na] at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
~[jfxrt.jar:na] at
test.spring.boot.config.SpringFXMLLoader.load(SpringFXMLLoader.java:34)
~[bin/:na] at
test.spring.boot.config.StageManager.loadViewNodeHierarchy(StageManager.java:80)
[bin/:na] at
test.spring.boot.config.StageManager.switchScene(StageManager.java:31)
[bin/:na] at test.spring.boot.Main.displayInitialScene(Main.java:35)
[bin/:na] at test.spring.boot.Main.start(Main.java:24) [bin/:na] at
com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
[jfxrt.jar:na] at
com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
~[jfxrt.jar:na] at
com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
~[jfxrt.jar:na] at java.security.AccessController.doPrivileged(Native
Method) ~[na:1.8.0_131] at
com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
~[jfxrt.jar:na] at
com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
~[jfxrt.jar:na] at com.sun.glass.ui.win.WinApplication._runLoop(Native
Method) ~[jfxrt.jar:na] at
com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
~[jfxrt.jar:na] at java.lang.Thread.run(Unknown Source)
~[na:1.8.0_131]
2017-10-24 17:18:03.846 INFO 6416 --- [lication Thread]
s.c.a.AnnotationConfigApplicationContext : Closing
org.springframework.context.annotation.AnnotationConfigApplicationContext#f096164:
startup date [Tue Oct 24 17:18:02 IST 2017]; root of context hierarchy
2017-10-24 17:18:03.848 INFO 6416 --- [lication Thread]
o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed
beans on shutdown java.lang.reflect.InvocationTargetException 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
com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at
com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
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
sun.launcher.LauncherHelper$FXHelper.main(Unknown Source) Caused by:
java.lang.RuntimeException: Exception in Application start method at
com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at
com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Unknown Source) Caused by:
java.lang.NullPointerException: Root cannot be null at
javafx.scene.Scene.(Scene.java:336) at
javafx.scene.Scene.(Scene.java:194) at
test.spring.boot.config.StageManager.prepareScene(StageManager.java:62)
at test.spring.boot.config.StageManager.show(StageManager.java:36) at
test.spring.boot.config.StageManager.switchScene(StageManager.java:32)
at test.spring.boot.Main.displayInitialScene(Main.java:35) at
test.spring.boot.Main.start(Main.java:24) at
com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at
com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at
com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method) at
com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at
com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at
com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more Exception running application test.spring.boot.Main
Main.java
#ComponentScan("test.spring.boot")
#SpringBootApplication
public class Main extends Application {
protected ConfigurableApplicationContext springContext;
protected StageManager stageManager;
#Override
public void start(Stage primaryStage) throws IOException {
stageManager = springContext.getBean(StageManager.class, primaryStage);
displayInitialScene();
}
#Override
public void init() throws Exception
{
springContext=springBootApplicationContext();
}
protected void displayInitialScene() {
stageManager.switchScene(FxmlView.LOGIN);
}
#Override
public void stop() throws Exception {
springContext.close();
}
private ConfigurableApplicationContext springBootApplicationContext() {
SpringApplicationBuilder builder = new SpringApplicationBuilder(Main.class);
String[] args = getParameters().getRaw().stream().toArray(String[]::new);
return builder.run(args);
}
public static void main(String[] args) {
Application.launch(args);
}
}
Controller.java
public class LoginPageController implements Initializable{
#FXML
private TextField txtUserName;
#FXML
private PasswordField txtPassward;
#FXML
private Button btnLogin;
#FXML
private Label lblLogin;
#Autowired
private UserService userService;
#Lazy
#Autowired
private StageManager stageManager;
#FXML
public void login()
{
if(userService.authenticate(txtUserName.getText(), txtPassward.getText()))
{
stageManager.switchScene(FxmlView.USER);
}
else
{
lblLogin.setText("Login Failed.");
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
}
}
FxmlView.java
public enum FxmlView {
USER {
#Override
public String getTitle() {
return getStringFromResourceBundle("user.title");
}
#Override
public String getFxmlFile() {
return "/test/spring/boot/TestSpring.fxml";
}
},
LOGIN {
#Override
public String getTitle() {
return getStringFromResourceBundle("login.title");
}
#Override
public String getFxmlFile() {
return "/test/spring/boot/LoginPage.fxml";
}
};
public abstract String getTitle();
public abstract String getFxmlFile();
String getStringFromResourceBundle(String key){
return ResourceBundle.getBundle("Bundle").getString(key);
}
}
SpringFxmlLoader.java
#Component
public class SpringFXMLLoader {
private final ResourceBundle resourceBundle;
private final ApplicationContext context;
#Autowired
public SpringFXMLLoader(ApplicationContext context, ResourceBundle resourceBundle) {
this.resourceBundle = resourceBundle;
this.context = context;
}
public Parent load(String fxmlPath) throws IOException {
FXMLLoader loader = new FXMLLoader();
loader.setControllerFactory(context::getBean); //Spring now FXML Controller Factory
loader.setResources(resourceBundle);
loader.setLocation(getClass().getResource(fxmlPath));
System.out.println("springfxmlloader class : "+fxmlPath);
System.out.println("LOADER : ");
return loader.load();
}
}
StageManager.java
public class StageManager {
private static final Logger LOG = getLogger(StageManager.class);
private final Stage primaryStage;
private final SpringFXMLLoader springFXMLLoader;
public StageManager(SpringFXMLLoader springFXMLLoader, Stage stage) {
System.out.println(">>>>>>>>>>>>>>>>>> 1");
this.springFXMLLoader = springFXMLLoader;
this.primaryStage = stage;
}
public void switchScene(final FxmlView view) {
System.out.println(">>>>>>>>>>>>>>>>>> 2");
Parent viewRootNodeHierarchy = loadViewNodeHierarchy(view.getFxmlFile());
show(viewRootNodeHierarchy, view.getTitle());
}
private void show(final Parent rootnode, String title) {
Scene scene = prepareScene(rootnode);
//scene.getStylesheets().add("/styles/Styles.css");
//primaryStage.initStyle(StageStyle.TRANSPARENT);
primaryStage.setTitle(title);
primaryStage.setScene(scene);
primaryStage.sizeToScene();
primaryStage.centerOnScreen();
System.out.println(">>>>>>>>>>>>>>>>>> 3");
try {
primaryStage.show();
} catch (Exception exception) {
logAndExit ("Unable to show scene for title" + title, exception);
}
}
private Scene prepareScene(Parent rootnode){
System.out.println(">>>>>>>>>>>>>>>>>> 4");
Scene scene = primaryStage.getScene();
System.out.println("SCN >>>>>>>>>>>>>>>>>>>> : "+ scene);
if (scene == null) {
scene = new Scene(rootnode);
}
scene.setRoot(rootnode);
return scene;
}
private Parent loadViewNodeHierarchy(String fxmlFilePath) {
System.out.println(">>>>>>>>>>>>>>>>>> 5 path: "+fxmlFilePath);
Parent rootNode = null;
try {
System.out.println(fxmlFilePath);
rootNode = springFXMLLoader.load(fxmlFilePath);
System.out.println(">>>>5 : try");
Objects.requireNonNull(rootNode, "A Root FXML node must not be null");
} catch (Exception exception) {
System.out.println("File path????? : "+fxmlFilePath);
logAndExit("Unable to load FXML view >> " + fxmlFilePath, exception);
exception.printStackTrace();
}
return rootNode;
}
private void logAndExit(String errorMsg, Exception exception) {
System.out.println(">>>>>>>>>>>>>>>>>> 6");
LOG.error(errorMsg, exception, exception.getCause());
Platform.exit();
}
}
You forgot to add a Stereotype on your LoginPageController class that's why Spring is telling you:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'test.spring.boot.LoginPageController'
As the class is not marked the component-scan will ignore it and there will be no bean register assignable for that type.
Try:
#Controller
public class LoginPageController implements Initializable{
#Autowired
public LoginPageController(UserService userService, private StageManager stageManager){
this.userService = userService;
this.stageManager = stageManager;
}
}
We're running GraphQL sample Java application in WebLogic 12c, but encountered some errors with servlet during startup.
The servlet was configured and register our servlets using a ServletRegistrationBean as below:
#Configuration
#ConditionalOnWebApplication
#ConditionalOnClass(DispatcherServlet.class)
#ConditionalOnBean({GraphQLSchema.class, GraphQLSchemaProvider.class})
#ConditionalOnProperty(value = "graphql.servlet.enabled", havingValue = "true", matchIfMissing = true)
#AutoConfigureAfter({GraphQLJavaToolsAutoConfiguration.class, SpringGraphQLCommonAutoConfiguration.class})
#EnableConfigurationProperties(GraphQLServletProperties.class)
public class GraphQLWebAutoConfiguration {
...
#Bean
#ConditionalOnMissingBean
public GraphQLServlet graphQLServlet(GraphQLSchemaProvider schemaProvider, ExecutionStrategyProvider executionStrategyProvider) {
return new SimpleGraphQLServlet(schemaProvider, executionStrategyProvider, listeners, instrumentation, errorHandler, contextBuilder);
}
#Bean
ServletRegistrationBean graphQLServletRegistrationBean(GraphQLServlet servlet) {
ServletRegistrationBean bean = new ServletRegistrationBean(servlet, graphQLServletProperties.getServletMapping());
bean.setLoadOnStartup(1);
return bean;
}
}
In the weblogic server log, it prints out errors:
<Oct 2, 2017 1:51:28 PM SGT> <Error> <HTTP> <BEA-101125> <[ServletContext#933807824[app:CPRES module:CPRES path:null spec-version:3.1]] Error occurred while instantiating servlet: "simpleGraphQLServlet".
java.lang.InstantiationException: graphql.servlet.SimpleGraphQLServlet
at java.lang.Class.newInstance(Class.java:427)
at weblogic.servlet.internal.WebComponentContributor.getNewInstance(WebComponentContributor.java:252)
at weblogic.servlet.internal.WebComponentContributor.getNewInstance(WebComponentContributor.java:245)
at weblogic.servlet.internal.WebComponentContributor.createServletInstance(WebComponentContributor.java:274)
at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.newServletInstanceIfNecessary(StubSecurityHelper.java:365)
Truncated. see log file for complete stacktrace
Caused By: java.lang.NoSuchMethodException: graphql.servlet.SimpleGraphQLServlet.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)
at weblogic.servlet.internal.WebComponentContributor.getNewInstance(WebComponentContributor.java:252)
at weblogic.servlet.internal.WebComponentContributor.getNewInstance(WebComponentContributor.java:245)
at weblogic.servlet.internal.WebComponentContributor.createServletInstance(WebComponentContributor.java:274)
Truncated. see log file for complete stacktrace
>
<Oct 2, 2017 1:51:28 PM SGT> <Error> <HTTP> <BEA-101216> <Servlet: "simpleGraphQLServlet" failed to preload on startup in Web application: "CPRES".
javax.servlet.ServletException: Servlet class: 'graphql.servlet.SimpleGraphQLServlet' couldn't be instantiated
at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:326)
at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:294)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:326)
at weblogic.security.service.SecurityManager.runAsForUserCode(SecurityManager.java:196)
at weblogic.servlet.provider.WlsSecurityProvider.runAsForUserCode(WlsSecurityProvider.java:203)
Truncated. see log file for complete stacktrace
>
<Oct 2, 2017 1:51:29 PM SGT> <Error> <Deployer> <BEA-149265> <Failure occurred in the execution of deployment request with ID "19094957742917053" for task "130" on [partition-name: DOMAIN]. Error is: "weblogic.application.ModuleException: javax.servlet.ServletException: Servlet class: 'graphql.servlet.SimpleGraphQLServlet' couldn't be instantiated"
weblogic.application.ModuleException: javax.servlet.ServletException: Servlet class: 'graphql.servlet.SimpleGraphQLServlet' couldn't be instantiated
It looks that the weblogic is trying to create a new servlet instance instead of the ServletBean SimpleGraphQLServlet created and managed by Spring context.
Any advance? Thanks.
A walkaround solution is to write a Servlet wrapper class like this:
public class DelegateGraphQLServlet extends HttpServlet {
protected GraphQLServlet graphQLServlet;
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
ApplicationContext ac = (ApplicationContext) servletConfig.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
this.graphQLServlet = (GraphQLServlet)ac.getBean("graphQLServlet");
}
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
graphQLServlet.service(req, res);
}
}
I'm using full java based configuration for a project.
When deploying webapp, I get the following error :
Sep 06, 2016 8:13:37 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Sep 06, 2016 8:13:37 AM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Sep 06, 2016 8:13:37 AM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Tue Sep 06 08:13:37 CEST 2016]; root of context hierarchy
Sep 06, 2016 8:13:38 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/net.brewspberry.util.SpringWebappConfiguration]
Sep 06, 2016 8:13:38 AM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/net.brewspberry.util.SpringWebappConfiguration]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/net.brewspberry.util.SpringWebappConfiguration]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:612)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:513)
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:4813)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5272)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/net.brewspberry.util.SpringWebappConfiguration]
at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:141)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 21 more
The thing is I don't get why Spring tries to load an XML config while I registered a Class config :
WebappInitializer :
package net.brewspberry.util.config;
import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import net.brewspberry.filters.AuthentificationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringWebappInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer implements
WebApplicationInitializer {
public void onStartup(ServletContext servletContext)
throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.setServletContext(servletContext);
// rootContext.setConfigLocation("net.brewspberry.util");
rootContext.register(SpringCoreConfiguration.class);
servletContext.addListener(new ContextLoaderListener(rootContext));
// now the config for the Dispatcher servlet
AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
// mvcContext.setConfigLocation("net.brewspberry.util.config");
//mvcContext.register(SpringWebappConfiguration.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"DispatcherServlet", new DispatcherServlet(mvcContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("*.do");
}
#Override
protected Filter[] getServletFilters() {
return null; // new Filter[] { new AuthentificationFilter() };
}
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return null;
}
}
Webapp config :
package net.brewspberry.util.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan({ "net.brewspberry" })
public class SpringWebappConfiguration extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/login.jsp");
}
#Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
I have no web.xml necesary as WebAppInitializer replaces it. I tried with or without that line :
mvcContext.register(SpringWebappConfiguration.class);
but it does not change anything.
Moreover, in logs, Spring searches for XML application context while in initializer it is defined as an annotation application context. I don't get it...
Any idea ?
You have to specify dispatcher servlet to use SpringWebappConfiguration as it context or set SpringWebappConfiguration as applicationRoot context.
I am in the proces of creating simple CRUD program with Spring data rest Spring data rest,
but I have a problem with security configuration (example was taken from here.
I have a WebAppInitializer:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{JpaRepositoryConfig.class, SecurityConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{CustRepositoryRestMvcConfiguration.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Filter[] getServletFilters() {
return new Filter[]{ new DelegatingFilterProxy("springSecurityFilterChain")};
}
}
I have a next crud repository:
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.repository.annotation.RestResource;
import org.springframework.security.access.prepost.PreAuthorize;
#PreAuthorize("hasRole('ROLE_USER')")
#RestResource(path = "products", rel = "products")
public interface ProductRepository extends PagingAndSortingRepository<Product, Long> {
#PreAuthorize("hasRole('ROLE_ADMIN')")
#Override
Product save(Product s);
#PreAuthorize("hasRole('ROLE_ADMIN')")
#Override
void delete(Long aLong);
}
I have a next security configuration:
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("greg").password("turnquist").roles("USER").and()
.withUser("ollie").password("gierke").roles("USER", "ADMIN");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/products").hasRole("ADMIN")
.antMatchers(HttpMethod.PUT, "/products/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PATCH, "/products/**").hasRole("ADMIN").and()
.csrf().disable();
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
I used next version of dependencies:
<java-version>1.7</java-version>
<spring-data-rest-version>1.0.0.RELEASE</spring-data-rest-version>
<spring.version>3.2.2.RELEASE</spring.version>
<org.slf4j-version>1.7.5</org.slf4j-version>
From project configured log4j I am getting these errors:
SEVERE: Error filterStart
org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/admin] startup failed due to previous errors
INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationCon
text - Closing Root WebApplicationContext: startup date [Tue Dec 30 00:09:21 EET
2014]; root of context hierarchy
......
DEBUG: org.springframework.beans.factory.support.DisposableBeanAdapter - Invokin
g destroy() on bean with name 'org.springframework.security.config.annotation.au
thentication.configuration.AuthenticationConfiguration'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Re
trieved dependent beans for bean '(inner bean)': [(inner bean), productRepositor
y]
DEBUG: org.springframework.beans.factory.support.DisposableBeanAdapter - Invokin
g destroy() on bean with name 'securityConfig'
From tomcat 7.0.56 localhost log I also have these errors in the logs:
SEVERE: Exception starting filter delegatingFilterProxy
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:568)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1102)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:278)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1121)
at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:326)
at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:236)
at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:194)
at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:109)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4830)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5510)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1083)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1879)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
What is causing the errors in these logs?