2016-03-28 321 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,並且從來沒有這樣做過。

相關問題