1. How can we set the active profile in Java code instead of using web.xml?
Why: In Spring MVC, a WebApplicationInitializer implementation can set the active profile in Java code by setting the spring.profiles.active init parameter on the ServletContext. For example: servletContext.setInitParameter("spring.profiles.active", "dev");
2. Which init parameter name is used to set the active profiles?
Why: The init parameter spring.profiles.active tells Spring which profile is active. Its value is the profile name, for example dev.
3. Which method of an initializer class do we override to set the profile parameter?
Why: The onStartup(ServletContext) method is called when the web application starts. It gives us the ServletContext, so we can set the profile parameter there.
4. Which method call sets the active profile to dev?
public void onStartup(ServletContext ctx)
throws ServletException {
ctx.______("spring.profiles.active", "dev");
}
Why:ServletContext.setInitParameter(name, value) sets an init parameter. Using the name spring.profiles.active with the value dev makes dev the active profile.
5. A bean is annotated with @Profile("default"). When is this bean created?
Why: The default profile is used when no profile is active. A bean marked with @Profile("default") is created only in that case.
6. Which annotation makes this bean available only when the dev profile is active?
@Service
public class DevMailSender
implements MailSender {
}
Why:@Profile("dev") registers the bean only when the dev profile is active. The other annotations do not exist in Spring for this purpose.
7. A controller returns the message of the injected Msg bean. What does a request to / return?
@Service
@Profile("default")
class LocalMsg implements Msg {
public String get() { return "local"; }
}
@Service
@Profile("prod")
class ProdMsg implements Msg {
public String get() { return "prod"; }
}
public void onStartup(ServletContext ctx)
throws ServletException {
ctx.setInitParameter(
"spring.profiles.active", "prod");
}
Why: The active profile is prod, so only ProdMsg is created. The default profile is not used when another profile is active, so LocalMsg is not created.