我有一个名为circle的简单类,其具有称为center的属性,我有一个名为circle的简单类,其具有称为center的属性,在其上我应用了@Resource批注以注入来自spring.xml的依赖关系,但是中心值是不从spring.xml注入,这就是为什么我在获取值时获取空指针异常的原因。
我有一个在xml中定义的bean,其名称与circle属性的名称相同


     //Circle class:

        package org.devesh.learning.spring;

        import javax.annotation.Resource;

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

public class Circle implements Shape {

    private Point center;

    @Override
    public void draw() {

      System.out.println("Circle drawn");
      System.out.println("Circle center is : "+ center.getX() + "," + center.getY());
    }

    public Point getCenter() {
        return center;
    }

    //@Autowired
    //@Qualifier("circle related")
    @Resource
    public void setCenter(Point center) {
        this.center = center;
    }

}


Point class:

package org.devesh.learning.spring;

public class Point {

    private int x;
    private int y;


    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }



}

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 https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
         https://www.springframework.org/schema/context/spring-context-3.2.xsd"
    xmlns:context="http://www.springframework.org/schema/context/spring-context-3.2.xsd">

     <bean id="circle" class="org.devesh.learning.spring.Circle">
     </bean>

       <bean id ="pointA"  class="org.devesh.learning.spring.Point">
      <property name="x" value="${pointA.pointX}"></property>
      <property name="y" value="${pointA.pointY}"></property>
  </bean>


   <bean id = "center" class="org.devesh.learning.spring.Point">
      <property name="x" value="20"></property>
      <property name="y" value="0"></property>
  </bean>


  <bean id = "pointC" class="org.devesh.learning.spring.Point">
      <property name="x" value="-20"></property>
      <property name="y" value="0"></property>
  </bean>

   <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="locations" value="pointconfig.properties"></property>
 </bean>



</beans>

最佳答案

您有多个相同点类型的bean,通过其ID注入中心,
@Resource(name =“ center”)

How do I inject a Spring dependency by ID?

关于java - 在使用getter方法获取值时,应用于setter方法的@Resource批注将返回空指针异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58145791/

10-10 16:52