Engineering Full Stack Apps with Java and JavaScript
Create a basic Spring program that uses Profiles.
@Profile annotation allow you to register components that will be selected only if its associated profile is active. You can selectively activate a set of beans in a class or all beans .
JJWriter.java
package com.javajee.spring;
public interface JJWriter {
public void write();
}
JJFileWriter.java
package com.javajee.spring;
public class JJFileWriter implements JJWriter {
public void write() {
System.out.println("Writing to file!!!");
}}
JJDatabaseWriter.java
package com.javajee.spring;
public class JJDatabaseWriter implements JJWriter {
public void write() {
System.out.println("Writing to Database!!!");
}
}
DemoConfig.java
package com.javajee.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;@Configuration
public class DemoConfig {@Bean (name = "writer")
@Profile({"default","dbprofile"})
public JJWriter getJJDatabaseWriter()
{
return new JJDatabaseWriter();
}
@Bean (name = "writer")
@Profile("fileprofile")
public JJWriter getJJFileWriter()
{
return new JJFileWriter();
}
}
JJWriterMain.java
package com.javajee.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class JJWriterMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("fileprofile");
//Set profile and register config class
context.register(DemoConfig.class);
context.refresh();JJWriter writer = context.getBean("writer", JJWriter.class);
writer.write();
}
}
Check out different ways to activate profiles here.