gpt4 book ai didi

java - Spring - 我的 Autowiring 有什么问题?

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:10:40 26 4
gpt4 key购买 nike

我有这个基本的 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

最佳答案

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

how do I configure autowire in spring

关于java - Spring - 我的 Autowiring 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31159054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com