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

Spring - what is wrong with my Autowiring?

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

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>

Class执行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
you want to define @Quatifier

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

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

how do I configure autowire in spring

您需要在 spring.xml 文件中添加 <context:annotation-config/>,它将扫描 java 文件中的 spring 注释。希望这有帮助。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
    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
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config />

    <bean id="pi" name="pi" class="java.lang.Double">
        <constructor-arg value="3.14" />
    </bean>
    <bean id="helloWorld" class="com.clsa.test.HelloWorld">
        <constructor-arg ref="msg" />
    </bean>
    <bean id="msg" class="java.lang.String">
        <constructor-arg value="Hello World" />
    </bean>
</beans>