Engineering Full Stack Apps with Java and JavaScript
Activate a profile using properties file.
We can use the property 'spring.profiles.active' within a properties file to activate a profile and is the most preferred approach.
We will define this property in a file called application.properties and then import this properties file using @PropertySource on the Java configuration class. If you are using Spring Boot, then you don't have to import this file as Spring Boot automatically import a file names application.properties.
JJWriter.java
This class has not changed.
package com.javajee.spring;
public interface JJWriter {
public void write();
}
JJDatabaseWriter.java
package com.javajee.spring;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;@Component("writer")
@Profile({"default","dbprofile"})
public class JJDatabaseWriter implements JJWriter {public void write() {
System.out.println("Writing to Database!!!");
}
@Override
public String toString(){
return "Writing to Database!!!";
}
}
JJFileWriter.java
package com.javajee.spring;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component("writer")
@Profile("fileprofile")
public class JJFileWriter implements JJWriter {
public void write() {
System.out.println("Writing to File!!!");
}
@Override
public String toString(){
return "Writing to File!!!";
}
}
Create a properties file 'application.properties' in classpath with the property 'spring.profiles.active':
spring.profiles.active=dbprofile
DemoConfig.java
package com.javajee.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;@Configuration
@PropertySource("classpath:/application.properties")
@ComponentScan(basePackages="com.javajee.spring")
public class DemoConfig {}
JJWriterMain.java
package com.javajee.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;public class JJWriterMain {
public static void main(String[] args) {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class);
JJWriter writer = context.getBean("writer", JJWriter.class);
writer.write();
context.close();
}
}
Now change the profiles within properties file to test. If you use a profile that does not exist, you get a error that the bean could not be found. If you remove the profile property, then you can test the default profile.