【问题标题】:How to set @Required field in Spring without using the application-context.xml file?如何在不使用 application-context.xml 文件的情况下在 Spring 中设置 @Required 字段?
【发布时间】:2014-10-14 19:58:19
【问题描述】:

我正在使用 Spring-Boot,并且我正在尝试在不使用 application-context.xml 文件的情况下设置已实现服务的必需属性(即带有 @Required 标记的属性)。在我的 application-context.xml 文件中,服务如下所示:

<bean class="services.impl.MyServiceImpl">
    <property name="property" value="value" />
</bean>

我猜这些属性在 Java 中看起来像这样:

protected Properties buildMyServiceImplProperties()
{
    Properties myServiceImplProperties = new Properties();    
    myServiceImplProperties.setProperty("property", "value");
    return myServiceImplProperties;
}

编辑:服务类 MyService 定义如下:

package services;

public interface MyService {}

而实现是:

package services.impl;

import services.DoctorService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class MyServiceImpl implements MyService {

    private String value;

    @Required
    public void setProperty(String value) {
        this.value = value;
    }

}

【问题讨论】:

    标签: spring-mvc spring-boot spring-java-config


    【解决方案1】:

    不确定我是否理解你的问题,但如果你想在 Java Config 中创建那个 bean,你只需要这样的东西:

    @Bean
    public MyService(){
      MyService service = new MyServiceImpl();
      service.setProperty("property", "value");
      return service;
    }
    

    【讨论】:

    • 不,这不起作用,因为方法 setProperty 不是类的一部分。必须以某种方式注入属性以配置 @Bean。
    • @Gorayni 你能用 MyServiceImpl 更新你的帖子吗?
    猜你喜欢
    • 2016-06-15
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多