【问题标题】:setter method not working in Spring?setter 方法在 Spring 中不起作用?
【发布时间】:2014-05-09 05:31:49
【问题描述】:

我已尝试从上下文文件初始化 setter 方法。但它没有按预期工作。

//setter方法

public class Service {

    private long Id=0;

    public long getId() {
        return Id;
    }
    public void setId(long Id) {
        this.Id = Id;
    }

}

//调用方法

public class test {

    //...source code
    Service sercvi = new Service();
    System.out.println("******************ID"+sercvi.getId());
    .................................. 

}

上下文.xml

    ..........................................
    ..........................................
    <bean id="Service"  class="com.test.Service.Service" > 
      <property name="Id" value="100"/> 
    </bean>
   ...........................................
   ..........................................

这里在 web.xml 文件中加载上下文文件 web.xml

...............................
    ....................
    <!-- Spring load context.xml - -->
    <context-param>
        <param-name>contextLocation</param-name>
        <param-value>/WEB-INF/Context.xml</param-value>
    </context-param>

如果我运行应用程序,它总是为 id 返回 0 值,但我在 context.xml 中初始化了 100。 为什么没有检索到该值? 如何从上下文文件中初始化 setter 方法值? 还有如何检索这些值?

如何解决这个错误?

【问题讨论】:

    标签: java spring


    【解决方案1】:

    您的Service 实例正在手动创建。 Spring 只会在你的 bean 由 Spring 上下文处理时触发注入。

    如何解决这个错误?

    不要手动初始化您的 bean,使用 Spring 上下文或通过 Spring 注入来恢复它们。

    您可以将 bean 注入另一个 bean:

    @Component
    public class FooComponent {
        @Autowired
        Service service;
        public void foo() {
            System.out.println(service.getId()); //prints the value injected by Spring
        }
    }
    

    或者直接从Spring上下文中恢复

    @Component
    public class BarComponent {
        @Autowired
        BeanFactory beanFactory;
        void bar() {
            Service service = (Service)beanFactory.get("service");
            System.out.println(service.getId()); //prints the value injected by Spring
        }
    }
    

    还有另一个选项可以让您手动创建 bean 并使用 @Configurable 注释在其中获取所有 Spring power,如 here 所述。


    如果您想测试 Spring bean,请使用 JUnit + Spring Test,但这更多用于集成测试而不是单元测试。

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(location={"classpath:location/of/your/spring.xml"})
    public class MySpringTest {
        @Autowired
        Service service;
    
        @Test
        public void fooTest() {
            System.out.println(service.getId());
            Assert.assertEquals(100, service.getId());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-01
      • 2015-07-23
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      • 2021-03-26
      • 2012-01-31
      相关资源
      最近更新 更多