gpt4 book ai didi

java - 具有 AnnotationConfigApplicationContext : getting run time exception 的 Spring 应用程序

转载 作者:行者123 更新时间:2023-12-02 09:49:27 26 4
gpt4 key购买 nike

这是 one of my SO questions 的延续.

我扩展了相同的示例,并希望它能够工作,但是我收到了 NullPointerException。

完整的源代码如下:

FirstBean.java

package com.example;

import org.springframework.stereotype.Component;

@Component
public class FirstBean {

public FirstBean() {

}

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "FirstBean [name=" + name + "]";
}
}

SomeBean.java

package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Component
@Configuration
@ComponentScan(basePackages = { "com.example" })
public class SomeBean {

@Autowired
private FirstBean fb;

@Bean
FirstBean instantiateFirstBean() {
return new FirstBean();
}

public SomeBean() {
// this.fb.setName("Some Name"); -> this was causing problem as
// bean isn't still created fully
}

public void print() {
this.fb.toString();
}

@PostConstruct
void post() {
fb.setName("Some name");
}
}

MainDriver.java

package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;

@Configuration
@ComponentScan(basePackages = { "com.example" })
@PropertySource(ignoreResourceNotFound = true, value = "classpath:/application.props")
public class MainDriver {

@Autowired
private Environment env;

@Autowired
private ConfigurableEnvironment cenv;

@Autowired
ApplicationContext ctx;

@Autowired
private SomeBean sb;

@Bean
public SomeBean instantiateSomeBean() {
return new SomeBean();
}

public static void main(String[] args) {

ApplicationContext ctx = new AnnotationConfigApplicationContext(MainDriver.class);

MainDriver l = ctx.getBean(MainDriver.class);
System.out.println("In main() the ctx is " + ctx);
l.test();
}

public void test() {
System.out.println("hello");
sb.print();
}
}

我期待 SomeBean 获得 Autowired (ctx, env, cenv > 正在完美地 Autowiring ),但它没有得到,并且我遇到了运行时异常。

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mainDriver': Unsatisfied dependency expressed through field 'sb'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someBean' defined in file [/Users/vkoul/understand-code/platform/stream-base/trunk/target/classes/com/example/SomeBean.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.SomeBean$$EnhancerBySpringCGLIB$$fad3571b]: Constructor threw exception; nested exception is java.lang.NullPointerException
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mainDriver': Unsatisfied dependency expressed through field 'sb'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someBean' defined in file [/Users/vkoul/understand-code/platform/stream-base/trunk/target/classes/com/example/SomeBean.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.SomeBean$$EnhancerBySpringCGLIB$$fad3571b]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:370)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1336)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:548)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:88)
at com.example.MainDriver.main(MainDriver.java:37)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someBean' defined in file [/Users/vkoul/understand-code/platform/stream-base/trunk/target/classes/com/example/SomeBean.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.SomeBean$$EnhancerBySpringCGLIB$$fad3571b]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1228)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1135)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:581)
... 14 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.SomeBean$$EnhancerBySpringCGLIB$$fad3571b]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:182)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1220)
... 25 more
Caused by: java.lang.NullPointerException
at com.example.SomeBean.<init>(SomeBean.java:23)
at com.example.SomeBean$$EnhancerBySpringCGLIB$$fad3571b.<init>(<generated>)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:170)
... 27 more

我还提到了@Bean,我希望它能告诉我如何创建这些bean,但仍然遇到异常。

我不明白什么,我该如何解决它?

最佳答案

我认为这是因为 Spring 首先必须实例化您的 SomeBean 类,然后它会尝试通过反射 Autowiring FirstBean 因为您放置了 @Autowired 字段上的注释。

您正在尝试访问 SomeBean 构造函数中的 FirstBean 依赖项,但是当调用 SomeBean 的构造函数时,在创建上下文时,FirstBean 依赖项为 null,因为 Spring 尚未 Autowiring 依赖项 - 它会在对象创建后尝试通过反射 Autowiring 它。这就是为什么你会得到 NullPointerException 。同样的情况也发生在您的 SomeBean 类上 - 决定一种方法。

此外,您创建的类同时使用 @Configuration@Component 进行注释,这很奇怪。请引用this SO question查看潜在的错误。

此外,您的配置存在一些问题。您使用 @Component 注释来注释 FirstBean,并且仍然创建一个返回此类实例的 @Bean 带注释的方法。您应该决定一种方法 - 使用 @Bean 注释为应用程序上下文实例化它,或者使用 @Component 注释此类,然后让组件扫描自动为您创建它。

编辑:

您应该决定是要使用 @ComponentScan 还是要通过 @Bean 注释为上下文创建 Bean - 现在您正在混合不同的类型并且您当尝试按类型 Autowiring 时,会出现重复 bean 定义的错误,因为在您当前的实现中,您的上下文中将有 2 个用于 SomeBean 的 bean 和 2 个用于 FirstBean 的 bean - 它们只会有不同的 id。请注意,我在 NPE 期望中指出的错误与它无关。我将提出一个使用自动包裹扫描的解决方案:

FirstBean 类

@Component
public class FirstBean {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "FirstBean [name=" + name + "]";
}
}

SomeBean 类

@Component
public class SomeBean {

private FirstBean fb;

@Autowired
public SomeBean(FirstBean firstBean) {
this.fb = firstBean;
this.fb.setName("Some Name");
}

public void print() {
this.fb.toString();
}
}

MyConfig 类

@Configuration
@ComponentScan(basePackages = { "com.example" })
public class MyConfig {

}

MainDriver 类

@Component
public class MainDriver {

@Autowired
private Environment env;

@Autowired
protected ConfigurableEnvironment cenv;

@Autowired
ApplicationContext ctx;

@Autowired
private SomeBean sb;


public static void main(String[] args) {

ApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class);

MainDriver l = ctx.getBean(MainDriver.class);
System.out.println("In main() the ctx is " + ctx);
l.test();
}

public void test() {
System.out.println("hello");
sb.print();
}
}

关于java - 具有 AnnotationConfigApplicationContext : getting run time exception 的 Spring 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56415496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com