2014-12-09 130 views
1

創建我的ApplicationContext時,myBean構造函數已成功使用。 但創建豆後,使用@Autowired標籤的null@Autowired Spring NullPointerException ApplicationContext創建後的空Bean

我雖然@Autowired會以某種方式取代getBean()?我得到這個錯誤?

爲什麼我需要調用GetBean,當我已經創建了我的Beans(在ApplicationContext啓動過程中)並且還自動裝配它們?

這是我迄今所做的:

主營:

@EnableAutoConfiguration 
@Configuration 
@ComponentScan("com.somePackage") 
public class Main { 
    ApplicationContext ctx= new AnnotationConfigApplicationContext(AppConfig.class); 

    SomeBean myBean = ctx.getBean(SomeBean.class); 
    myBean.doSomething();//succeeds 

    AnyOtherClass aoc = new AnyOtherClass();//Nullpointer (see AnyOtherClass.class for details) 

} 

AnyOtherClass:

public class AnyOtherClass { 
    @Autowired 
    protected SomeBean someBean; 

    public AnyOtherClass(){ 
     someBean.doSomething();//Nullpointer 
    } 

的AppConfig:

@Configuration 
public class AppConfig { 
    @Bean 
    @Autowired 
    public SomeBean BeanSomeBean() { 
     return new SomeBean(); 
    } 
} 

爲myBean:

public class SomeBean { 
    public SomeBean(){} 
    public void doSomething() { 
     System.out.println("do Something.."); 
    } 
} 

注:接口ApplicationContextAware工作正常,但沒有@Autowired。我真的很想和@Autowired一起去,因爲它聽起來更舒服,對我來說更不容易。

+1

使'AnyOtherClass'具有'@ Component'註釋並確保自動掃描看到它 – EpicPandaForce 2014-12-09 12:47:13

回答

2

要使@AutowiredAnyOtherClass中工作,AnyOtherClass需要是Spring bean。
像這樣

的AppConfig

@Configuration 
public class AppConfig { 
    @Bean 
    @Autowired 
    public SomeBean BeanSomeBean() { 
     return new SomeBean(); 
    } 

    @Bean 
    @Autowired 
    public AnyOtherClass BeanAnyOtherClass() { 
     return new AnyOtherClass(); 
    } 
} 

主要

@EnableAutoConfiguration 
@Configuration 
@ComponentScan("com.somePackage") 
public class Main { 
    ApplicationContext ctx= new AnnotationConfigApplicationContext(AppConfig.class); 

    SomeBean myBean = ctx.getBean(SomeBean.class); 
    myBean.doSomething();//succeeds 

    AnyOtherClass aoc = ctx.getBean(AnyOtherClass.class); 

} 

如果實例使用new AnyOtherClass()類,它會繞過春天,沒有註釋的將工作 。你必須把它從Spring上下文中取出,以便它成爲一個Spring bean。

+0

我將它解釋爲AppConfig中的Bean,我在Main.class中加載它。或者你的意思是在兩個地方將它定義爲Bean(AppConfig&AnyOtherClass)? – Hansa 2014-12-09 12:46:44

+0

@Hansa爲了清楚我的意思,我不是在談論'SomeBean'類,而是使用'@ Autowired'注入它的類。因此,'SomeBean'已經是一個Spring bean(在'AppConfig'中聲明),但是'AnyOtherClass'也需要是一個Spring bean(用'AppConfig'聲明,或者用'@ Component'註釋,位於一個包掃描('com.somePackage')) – 2014-12-09 12:51:50

+0

嗯,這對我來說意味着我添加了@autowired static AnyOtherClass aoc到Main。 ('靜態'因爲它的主..) 然後,我得到:BeanCreationException-> BeanInstantiationException->嵌套異常是java.lang.NullPointerException – Hansa 2014-12-09 13:00:18

0

嘗試

@Component 
public class AnyOtherClass { 
@Autowired 
protected SomeBean someBean; 

public AnyOtherClass(){ 
    someBean.doSomething();//Nullpointer 
} 

此外,你需要確保這個類是com.somePackage包。

+0

感謝您的回覆 - 但不會改變我=( – Hansa 2014-12-09 13:03:54