我遇到了一个我不知道如何解决的问题。我使用Spring Boot创建了Restful API,并且正在实现DTO-Domain-Entity模式,因此在这种特殊情况下,我具有此 Controller 的方法

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<UserResponseDTO> createUser(@RequestBody UserRequestDTO data) {
    UserDomain user = this.mapper.map(data, UserDomain.class);
    UserDomain createdUser = this.service.createUser(user);
    UserResponseDTO createdUserDTO = this.mapper.map(createdUser, UserResponseDTO.class);
    return new ResponseEntity<UserResponseDTO>(createdUserDTO, HttpStatus.CREATED);
}

public class UserDomain {

    private Long id;

    private Date createdDate;

    private Date updatedDate;

    private String username;

    private String password;

    @Value("${default.user.enabled:true}") // I have default-values.properties being loaded in another configuration file
    private Boolean enabled;
}

我正在将UserRequestDTO对象转换为UserDomain。据我了解,UserRequestDTO是正在注入(inject)的bean。然后我将其转换为UserDomain,这里的问题是UserDomain对象不是组件,因此enabled属性将不采用默认值。

如果我不想将UserDomain当作bean处理,我该如何使spring加载默认值(在这种情况下只是启用属性)?

编辑

答案不一样,因为我的目标是使用@Value批注完成它。

无论如何,这样做会是康斯坦丁建议的更好的方法吗?
public class UserDomain {

    @Autowired
    private Environment environment;

    private Boolean enabled;

    UserDomain(){
         this.enabled = environment.getProperty("default.user.enabled");
         // and all the other ones
    }

}

最佳答案

如果您的映射器有一个采用已经准备好的实例的方法,而不是Class,那么您可以添加原型(prototype)作用域的UserDomain bean并从 Controller 方法中调用context.getBean()

Controller

...

@Autowired
private WebApplicationContext context;

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<UserResponseDTO> createUser(@RequestBody UserRequestDTO data) {
    UserDomain user = this.mapper.map(data, getUserDomain());
    UserDomain createdUser = this.service.createUser(user);
    UserResponseDTO createdUserDTO = this.mapper.map(createdUser, UserResponseDTO.class);
    return new ResponseEntity<UserResponseDTO>(createdUserDTO, HttpStatus.CREATED);
}

private UserDomain getUserDomain() {
    return context.getBean(UserDomain.class);
}

...

Spring 配置
@Configuration
public class Config {

    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer propConfigurer = new PropertySourcesPlaceholderConfigurer();
        propConfigurer.setLocation(new ClassPathResource("application.properties"));
        return propConfigurer;
    }

    @Bean
    @Scope("prototype")
    public UserDomain userDomain() {
        return new UserDomain();
    }

    ...
}

否则,您可以使用 @Configurable 和AspectJ编译时编织。但是,您必须决定是否值得在您的项目中引入编织,因为您还有其他方法可以处理这种情况。

pom.xml
...

<!-- additional dependencies -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>4.2.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.8.6</version>
</dependency>

...

<!-- enable compile-time weaving with aspectj-maven-plugin -->
<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
            <version>1.7</version>
            <configuration>
                <complianceLevel>1.8</complianceLevel>
                <encoding>UTF-8</encoding>
                <aspectLibraries>
                    <aspectLibrary>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-aspects</artifactId>
                    </aspectLibrary>
                </aspectLibraries>
                <Xlint>warning</Xlint>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                        <goal>test-compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

...

UserDomain.java
@Configurable
public class UserDomain {

    private Long id;

    private Date createdDate;

    private Date updatedDate;

    private String username;

    private String password;

    @Value("${default.user.enabled:true}")
    private Boolean enabled;

    ...
}

Spring 配置

@EnableSpringConfigured<context:spring-configured>相同。
@Configuration
@EnableSpringConfigured
public class Config {

    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer propConfigurer = new PropertySourcesPlaceholderConfigurer();
        propConfigurer.setLocation(new ClassPathResource("application.properties"));
        return propConfigurer;
    }

    ...
}

请引用Spring文档以获取有关AspectJ and @Configurable的更多信息。

编辑

关于您的编辑。

请注意,您在此处使用 @Autowired 。这意味着UserDomain实例必须由Spring容器进行管理。容器不知道在其外部创建的实例,因此 @Autowired (确切地说是 @Value )将无法解析此类实例,例如UserDomain userDomain = new UserDomain()UserDomain.class.newInstance()。因此,您仍然必须在上下文中添加原型(prototype)作用域的UserDomain bean。实际上,这意味着建议的方法与 @Value 相关的方法类似,不同之处在于它将UserDomain与Spring Environment 相关联。因此,这是不好的。

仍然可以使用 Environment ApplicationContextAware 设计更好的解决方案,而无需将域对象绑定(bind)到Spring。

ApplicationContextProvider.java
public class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public static <T> T getEnvironmentProperty(String key, Class<T> targetClass, T defaultValue) {
        if (key == null || targetClass == null) {
            throw new NullPointerException();
        }

        T value = null;
        if (applicationContext != null) {
            System.out.println(applicationContext.getEnvironment().getProperty(key));
            value = applicationContext.getEnvironment().getProperty(key, targetClass, defaultValue);
        }
        return value;
    }

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
}

UserDomain.java
public class UserDomain {

    private Boolean enabled;

    public UserDomain() {
         this.enabled = ApplicationContextProvider.getEnvironmentProperty("default.user.enabled", Boolean.class, false);
    }

    ...
}

Spring 配置
@Configuration
@PropertySource("classpath:application.properties")
public class Config {

    @Bean
    public ApplicationContextProvider applicationContextProvider() {
        return new ApplicationContextProvider();
    }

    ...
}

但是,我不喜欢这种方法的额外复杂性和草率性。我认为这根本没有道理。

09-27 02:04