2016-03-28 320 views
0

我有一个数据对象(只有吸气剂\设定部),其需要知道的弹簧简档,即Java Spring - 如何将@Value注入数据对象?

@Value("${spring.profiles.active}") 
private String profile; 

我添加了一个逻辑到它的一个“集”的方法,它检查轮廓,即

public void setItem(Item msg) { 
    if (environmentProperties.isDevMode()) { 
     this.msg= msg; 
    } 
} 

,因为这个类是经常元帅\ unmarhsalled外部,因此,当然没有被填充@Value - 正弦我没有使用弹簧自动装配创建类的实例...我试图定义的类作为组件,并自动装载到包含配置文件@Value的外部类 - 但它不起作用 我使用spring 3.2 - 没有XML定义。

有什么建议吗?

b.t.w. 数据对象经常包装在一个异常类中 - 所以当它创建时,配置文件也应该被数据对象知道...

谢谢!

编辑:

  • 使用了ApplicationContextAware不工作 - 我得到空的 'setApplicationContext' 方法不会被调用。
  • 也试图直接获取上下文不起作用 - 使用时取代null: 'ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();'

FIXED: 我终于找到了一个例子如何staticly从外部类访问上下文:

@Configuration 
public class ApplicationContextContainer implements ApplicationContextAware { 

    private static ApplicationContext CONTEXT; 

    /** 
    * This method is called from within the ApplicationContext once it is 
    * done starting up, it will stick a reference to itself into this bean. 
    * 
    * @param context a reference to the ApplicationContext. 
    */ 
    @Override 
    public void setApplicationContext(ApplicationContext context) throws BeansException { 
     CONTEXT = context; 
    } 

    /** 
    * This is about the same as context.getBean("beanName"), except it has its 
    * own static handle to the Spring context, so calling this method statically 
    * will give access to the beans by name in the Spring application context. 
    * As in the context.getBean("beanName") call, the caller must cast to the 
    * appropriate target class. If the bean does not exist, then a Runtime error 
    * will be thrown. 
    * 
    * @param beanName the name of the bean to get. 
    * @return an Object reference to the named bean. 
    */ 
    public static Object getBean(String beanName) { 
     return CONTEXT.getBean(beanName); 
    } 
+0

您是否试过@DependsOn('yourPropertiesBeanName')? – Daniel

回答

0

如果我理解正确的话,你希望注入不是由Spring管理对象,但由其他一些内部调用new并返回对象的代码创建一个序列化框架。

要注入非托管对象,您需要配置加载时间或编译时编织。加载时编织需要一个代理参数和lib,当你启动虚拟机时,一些容器可能会为你做这件事。

编译时编织需要使用AspectJ编译器。

下面你会发现使用Maven和Spring启动一个完整的例子:

例如与运行:

mvn spring-boot:run -Drun.arguments="--spring.profiles.active=dev" 

DemoApplication.java:

package com.example; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Configurable; 
import org.springframework.beans.factory.annotation.Qualifier; 
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.aspectj.EnableSpringConfigured; 
import org.springframework.stereotype.Component; 

@SpringBootApplication 
public class DemoApplication { 
    @EnableSpringConfigured 
    @ComponentScan("com.example") 
    public static class AppConfiguration { 
     @Value("${spring.profiles.active}") 
     String profile; 

     @Bean 
     public String profile() { 
      return profile; 
     } 
    } 

    @Configurable 
    public static class SomePojo { 
     @Autowired 
     private String profile; 

     public void print() { 
      System.out.println(this + "\t" + profile); 
     } 
    } 

    @Component 
    public static class Runner { 
     public void run() { 
      new SomePojo().print(); 
      new SomePojo().print(); 
     } 
    } 

    public static void main(String[] args) { 
     SpringApplication.run(DemoApplication.class, args).getBean(Runner.class).run(); 
    } 

} 

的pom.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 
    <groupId>com.example</groupId> 
    <artifactId>demo</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <packaging>jar</packaging> 
    <name>demo</name> 
    <description>Demo project for Spring Boot</description> 
    <parent> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-parent</artifactId> 
     <version>1.3.3.RELEASE</version> 
     <relativePath /> <!-- lookup parent from repository --> 
    </parent> 
    <properties> 
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
     <java.version>1.8</java.version> 
    </properties> 
    <dependencies> 
     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter</artifactId> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-test</artifactId> 
      <scope>test</scope> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-aspects</artifactId> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-tx</artifactId> 
     </dependency> 
    </dependencies> 

    <build> 
     <plugins> 
      <plugin> 
       <groupId>org.codehaus.mojo</groupId> 
       <artifactId>aspectj-maven-plugin</artifactId> 
       <version>1.8</version> 
       <configuration> 
        <complianceLevel>1.8</complianceLevel> 
        <aspectLibraries> 
         <aspectLibrary> 
          <groupId>org.springframework</groupId> 
          <artifactId>spring-aspects</artifactId> 
         </aspectLibrary> 
        </aspectLibraries> 
       </configuration> 
       <executions> 
        <execution> 
         <id>compile</id> 
         <goals> 
          <goal>compile</goal> 
         </goals> 
        </execution> 
       </executions> 
      </plugin> 
      <plugin> 
       <groupId>org.springframework.boot</groupId> 
       <artifactId>spring-boot-maven-plugin</artifactId> 
      </plugin> 
     </plugins> 
    </build> 
</project> 
0

从你的描述,你试图注入都归到POJO,这是用于编组。通过这种结构,您可以寻找与基于静态/任何其他复杂解决方案不同的解决方法。

我建议将用作POJO的bean从依赖于属性值的逻辑中分离出来。您可以将该逻辑提取到BeanService(可放置到Spring上下文)并在该级别处理它,以便将服务和数据层之间的责任分开。

0

你做错了。您的代码不需要知道配置文件。在你的例子中,创建一个消息接口,以及这个接口的一些bean实现,每个配置文件都有一个实例,每个包含该配置文件的适当消息,并将每个配置文件分配给配置文件,以便为该配置文件实例化该bean,并将该实例注入需要消息的类中。

所以,

public interface Message { String getMessage(); } 

@Profile("dev") @Component 
public class DevMessage implements Message { 
    public String getMessage() { return "this is the dev message"; } 
} 

@Profile("prod") @Component 
public class ProdMessage implements Message { 
    public String getMessage() { return "this is the production message"; } 
} 

如果你喜欢形容贵@Configuration类的豆,你可以标记与@profile的整体结构,并有多种配置。

如果您将Message实例注入到类中,则可以在其上调用getMessage()。该配置文件将确保您有适合您的环境的适当实施。

编辑: 我刚刚重读你的问题,并意识到我有这个错误。你有实体对象存储在应用程序之外,并通过一些代码/框架实例化。这些不是弹簧组件,所以不能使用弹簧方法来进行依赖注入。在这种情况下,不要使用弹簧 - 它不工作,不需要工作,而且不应该工作。如果你没有通过弹簧实例化对象,那么它应该与弹簧无关。我不知道你的问题领域,但自从它发明以来,我一直在使用spring,并且从来没有这样做过。

相关问题