春天 - 我的自动装配有什么问题?

时间:2015-07-01 10:42:55

标签: java spring autowired

我有这个基本的spring应用程序,其中@Autowired字段的值在输出中为null。这有什么不对?

package com.spring;

import org.springframework.beans.factory.annotation.Autowired;

public class HelloWorld {
   private String message;

   @Autowired
   private Double pi;

   public HelloWorld(String message){
       this.message  = message;
   }

   public void setMessage(String message){
      this.message  = message;
   }

   public void getMessage(){
      System.out.println("Your Message : " + message);
      System.out.println("autowired: "+pi);
   }
}

spring.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-3.0.xsd">

    <bean id="pi" name="pi" class="java.lang.Double" autowire="byName">
        <constructor-arg value="3.14"/>
    </bean>


   <bean id="helloWorld" class="com.spring.HelloWorld">
        <constructor-arg ref="msg" />
   </bean>

    <bean id="msg" class="java.lang.String" >
        <constructor-arg value="Hello World"/>
    </bean>     

</beans>

执行APP的类:

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
      HelloWorld hw =  context.getBean(HelloWorld.class);
      hw.getMessage();
      System.out.println(context.getBean("msg"));



   }
}

输出结果为:

Your Message Hello World
autowired: null
Hello World

3 个答案:

答案 0 :(得分:3)

您需要配置上下文以允许自动装配。看到这个答案:

how do I configure autowire in spring

答案 1 :(得分:2)

您需要在spring.xml文件中添加init(frame:),该文件将扫描java文件中的spring注释。希望这会有所帮助。

init(name:)

答案 2 :(得分:0)

you want to define @Quatifier

@Autowired(required=true)
@Qualifier("pi")
Double pi;