2016-04-16 143 views
0

我有以下豆:春天注入不工作

Bean.java

import lombok.AllArgsConstructor; 
import lombok.Data; 

@Data 
@AllArgsConstructor 
public class Bean { 

    private String arg; 

} 

Service.java

import lombok.Getter; 
import javax.inject.Inject; 

public class Service { 

    @Inject @Getter 
    private Bean bean; 

    private String arg; 

    public Service(String arg) { 
     this.arg = arg; 
    } 
} 

這是我如何實例化那些事:

test-context.xml

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

    <bean class="com.example.Bean"> 
      <constructor-arg value="bean param"/> 
    </bean> 

    <bean class="com.example.Service"> 
      <constructor-arg value="service param"/> 
    </bean> 

</beans> 

但是,當我創建上下文,看看裏面是什麼Service例如:

ApplicationContext context = new ClassPathXmlApplicationContext("test-context.xml"); 
    System.out.println(context.getBean(Bean.class)); 
    System.out.println(context.getBean(Service.class).getBean()); 

第二System.out給我空。

爲什麼Bean實例沒有注入?

回答

1

我不確定您的方法是將XML配置與註釋混合和匹配,它需要<context:annotation-config/>。我會說你會以這樣或那樣的方式更安全。如果你堅持使用XML再注入XML定義的依賴

<bean id="foo" class="com.example.Bean"> 
    <constructor-arg value="bean param"/> 
</bean> 

<bean class="com.example.Service"> 
    <constructor-arg value="service param"/> 
    <property name="bean" ref="foo" /> 
</bean> 

或者做這一切與註釋

@Component 
public class Bean { 
    private String arg; 

    public Bean(@Value("{constructorArg}") final String arg) { 
     this.arg = arg; 
    } 
} 

@Service 
public class Service { 

    @Autowired @Getter 
    private Bean bean; 

    private String arg; 

    public Service(@Value("{constructorArg}") String arg) { 
     this.arg = arg; 
    } 
} 
2

我找到了原因,我忘了<context:annotation-config/>爲了使@Inject註釋工作。