Search code examples
xmlspringspring-java-config

xml to javaconfig: profile and properties


I want to convert the following spring beans from xml to a javaconfig class.

<bean name="recorder" class="Recorder" />    
<bean name="RecordFilter" class="RecordFilter">
    <property name="resourceLocation" value="classpath:ports.list" />
</bean>

<bean name="iRecorder" class="iRecorder">
    <property name="auditRecorder" ref="auditRecorder" />
</bean>

<beans profile="logging">
    <bean name="logger" class="Logger" />
</beans>

But I dont know how to write profile and ref in JavaConfig:

@Configuration
public class AppConfig {
    @Bean
    public Recorder recorder() {
        Recorder recorder = new Recorder();
        return recorder;
    }

    @Bean
    public Filter filter(){
        Filter filter = new Filter();
        filter.setResourceLocation("classpath:audit/ignoredports.list");
        return filter;
    }

    @Bean
    public Recorder recorder(){Recorder recorder = new Recorder();
        ???????
        return methodInvocationRecorder;
    }

    @Bean
    ??????????????

}

I saw the same request but didn`t find answer.


Solution

  • I am not 100% sure what you are trying to acheive, but this might point you in the right direction.

    Spring java config does allow for @Profile

    so taking your example:

    <beans profile="logging">
        <bean name="logger" class="Logger" />
    </beans>
    

    in java config it could be represented like this:

    @Configuration
    @Profile("logging")
    public class LoggingConfiguration {
    
        @Bean
        public Logger logger() {
            Logger myLogger = new Logger();
            return myLogger;
        }
    
    }
    

    Thus the logger bean will only be available/created when the "logging" profile is active.

    A simple way of activating a spring profile is by setting them in the property:

    spring.profiles.active=dev,logging
    

    This can also be overwritten via environment variables.

    For further extensive reading you can reference the docs: https://docs.spring.io/spring/docs/5.0.1.RELEASE/spring-framework-reference/core.html#beans-definition-profiles-java