2013-03-03 4 views
1

스프링을 통해 가져 오는 두 개의 빈을 가진 Java 응용 프로그램을 시도하고 있습니다. 하나는 이름으로 검색하고 하나는 자동으로 검색합니다.autowired 속성이 설정되지 않음

package firstspring; 

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 

public class FirstSpring 
{ 
    private final static Logger logger = LoggerFactory.getLogger(FirstSpring.class); 

    @Autowired 
    private Car currentCar; 
    public void setCurrentCar(Car car) { this.currentCar = car; } 
    public Car getCurrentCar() { return currentCar; } 

    private static void say(String message) { System.out.println(message); } 

    public static void main(String[] args) 
    { 
    FirstSpring firstSpring = new FirstSpring(); 
    firstSpring.go(); 
    } 

    public void go() 
    { 
    logger.info("here we go"); 
    ApplicationContext appContext = new ClassPathXmlApplicationContext("/appContext.xml"); 
    Car firstCar = (Car)appContext.getBean("firstCar"); 

    say ("firstCar was " + firstCar.getColor()); 
    say ("currentCar is " + currentCar.getColor()); 

    } 

} 

및 구성 :

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xsi:schemaLocation= 
      "http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-2.5.xsd"> 

     <context:annotation-config/> 

    <bean id="firstCar" class="firstspring.Car"> 
     <property name="color" value="blue" /> 
     <property name="doors" value="2" /> 
     <property name="transmission" value="automatic" /> 
    </bean> 

    <bean id="currentCar" class="firstspring.Car" > 
     <property name="color" value="red" /> 
     <property name="doors" value="4" /> 
     <property name="transmission" value="5-speed" /> 
    </bean> 

    <bean id="firstSpring" class="firstspring.FirstSpring"> 
      <property name="currentCar" ref="currentCar" /> 
    </bean> 

</beans> 

그리고 자동차 클래스는 그냥 완전하게 :

:
package firstspring; 

public class Car 
{ 
    String color; 
    int  doors; 
    String transmission; 

    public String getColor() { return color; } 
    public void setColor(String color) { this.color = color; } 

    public int getDoors() { return doors; } 
    public void setDoors(int doors) { this.doors = doors; } 

    public String getTransmission() { return transmission; } 
    public void setTransmission(String transmission) { this.transmission = transmission; } 
} 

내가 널 포인터 예외가 여기에 코드입니다
INFO: Pre-instantiating singletons in org.s[email protected]5e6458a6: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,firstCar,currentCar,firstSpring,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy 
Exception in thread "main" java.lang.NullPointerException 
    at firstspring.FirstSpring.go(FirstSpring.java:33) 
    at firstspring.FirstSpring.main(FirstSpring.java:23) 
firstCar was blue 

다양한 시도를 해봤습니다. r 것들 - 구성에서 currentCar bean에 'byName'을 두지 만, 필자가 읽은 문서에 따라 필요하다고 생각하지 않습니다. 내가 여기서 무엇을 놓치고 있니?

+0

'@ 한정자 '를 사용해보십시오 – madhead

+0

저는 아주 기본적인 스프링을 배우려고합니다. 그 후에 나는 그것의 다른 부분으로 나눌 수 있습니다. @Qualifier가 필요하다는 것에 대해서는 읽지 않았습니다. – arcy

+0

왜 downvote? 이것은 잘 질문입니다. –

답변

3

new FirstSpring()라고 말하면, 스프링의 컨트롤 밖에있는 그 클래스의 인스턴스를 생성하고 있습니다. 그래서 Spring은 그것을 autowire 할 수 없습니다. 따라서 currentCar.getColor()에 도달하면 currentCar은 null입니다. 이 작업을 올바르게 수행하려면 기본 메소드에 ApplicationContext을 만들고 Spring에서 FirstSpring 인스턴스를 가져와 객체를 직접 생성하는 대신 go()을 호출해야합니다. 한마디로

, 봄이 관리하지 않을 수 없다 (즉, 자동으로 묶어, 등, 파괴, 초기화) 그 자체를 만들지 않은 것을 모든 개체를. *

* 당신이 달성하기 위해 AspectJ with bytecode weaving을 사용하지 않는 이것은 AspectJ에 대한 다른 경험이 없다면, 아직 익숙하지 않은 고급 주제이다.

+0

감사합니다. 좋은 답변 :해야 할 일과 이유. "FirstCar 인스턴스를 Spring에서 가져 오기"를 "Spring에서 FirstSpring 인스턴스 가져 오기"로 변경하는 편집을 제출했습니다. 이는 분명히 사용자가 의도 한 것 ("해당 항목에 대한 호출")이기 때문입니다. 또한 첫 번째 줄을 들여 쓰면 Spring이 XML 파일을 처리하지 않는다는 것을 알게되었습니다 ... – arcy

+0

편집에 대한 호출이 좋습니다. XML의 빈 공간은 스프링이 아닙니다. XML 사양에 따르면 프롤로그 (첫 번째 줄)가 공백을 포함하여 파일의 맨 처음에 있어야합니다. –

관련 문제