Пролетни профили

1. Общ преглед

В този урок ще се съсредоточим върху въвеждането на профили през пролетта.

Профилите са основна характеристика на рамката - позволявайки ни да картографираме нашите зърна към различни профили - например dev , test и prod .

След това можем да активираме различни профили в различни среди, за да заредим само зърната, от които се нуждаем.

2. Използвайте @Profile на Bean

Нека започнем просто и да разгледаме как можем да направим така, че бобът да принадлежи към определен профил. Използваме анотацията @Profile - ние картографираме боб към този конкретен профил ; анотацията просто взема имената на един (или множество) профили.

Помислете за основен сценарий: Имаме боб, който трябва да бъде активен само по време на разработката, но не и да бъде внедрен в производството.

Анотираме този боб с dev профил и той ще присъства в контейнера само по време на разработката. В производството, DEV просто няма да бъде активен:

@Component @Profile("dev") public class DevDatasourceConfig

Като бърз страничен знак, имената на профилите могат също да бъдат с префикс с оператор NOT, например ! Dev , за да ги изключат от профил.

В примера компонентът се активира само ако dev profile не е активен:

@Component @Profile("!dev") public class DevDatasourceConfig

3. Декларирайте профили в XML

Профилите могат да бъдат конфигурирани и в XML. Thetag има атрибут profile , който приема стойности, разделени със запетая на приложимите профили:

4. Задайте профили

Следващата стъпка е да активирате и настроите профилите така, че съответните зърна да бъдат регистрирани в контейнера.

Това може да стане по различни начини, които ще разгледаме в следващите раздели.

4.1. Програмно чрез WebApplicationInitializer Interface

В уеб приложенията WebApplicationInitializer може да се използва за програмно конфигуриране на ServletContext .

Също така е много удобно място за програмиране на активните ни профили:

@Configuration public class MyWebApplicationInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { servletContext.setInitParameter( "spring.profiles.active", "dev"); } }

4.2. Програмно чрез ConfigurableEnvironment

Също така можем да зададем профили директно върху околната среда:

@Autowired private ConfigurableEnvironment env; ... env.setActiveProfiles("someProfile");

4.3. Контекстен параметър в web.xml

По същия начин можем да дефинираме активните профили във файла web.xml на уеб приложението, като използваме контекстен параметър:

 contextConfigLocation /WEB-INF/app-config.xml   spring.profiles.active dev 

4.4. JVM параметър на системата

Имената на профилите също могат да бъдат предадени чрез системния параметър на JVM. Тези профили ще бъдат активирани по време на стартиране на приложението:

-Dspring.profiles.active=dev

4.5. Променлива на околната среда

В Unix среда профилите могат да се активират и чрез променливата на средата :

export spring_profiles_active=dev

4.6. Профил на Maven

Пролетните профили могат да се активират и чрез Maven профили, като се зададе свойството конфигурация spring.profiles.active .

Във всеки профил на Maven можем да зададем свойство spring.profiles.active :

  dev  true   dev    prod  prod   

Стойността му ще бъде използвана за замяна на заместителя @ [имейл защитен] в application.properties :

[email protected]@

Сега трябва да активираме филтрирането на ресурси в pom.xml :

   src/main/resources true   ... 

и добавете параметър -P , за да превключите кой профил на Maven ще бъде приложен:

mvn clean package -Pprod

Тази команда ще опакова приложението за профил на прод . Това се отнася и за spring.profiles.active стойност остена за това приложение, когато е пуснат.

4.7. @ActiveProfile в тестове

Тестовете улесняват определянето на активните профили с помощта на анотацията @ActiveProfile за активиране на конкретни профили:

@ActiveProfiles("dev")

So far, we've looked at multiple ways of activating profiles. Let's now see which one has priority over the other and what happens if we use more than one, from highest to lowest priority:

  1. Context parameter in web.xml
  2. WebApplicationInitializer
  3. JVM System parameter
  4. Environment variable
  5. Maven profile

5. The Default Profile

Any bean that does not specify a profile belongs to the default profile.

Spring also provides a way to set the default profile when no other profile is active — by using the spring.profiles.default property.

6. Get Active Profiles

Spring's active profiles drive the behavior of the @Profile annotation for enabling/disabling beans. However, we may also wish to access the list of active profiles programmatically.

We have two ways to do it, using Environment or spring.active.profile.

6.1. Using Environment

We can access the active profiles from the Environment object by injecting it:

public class ProfileManager { @Autowired    private Environment environment;     public void getActiveProfiles() {         for (String profileName : environment.getActiveProfiles()) {             System.out.println("Currently active profile - " + profileName);         }       } }

6.2. Using spring.active.profile

Alternatively, we could access the profiles by injecting the property spring.profiles.active:

@Value("${spring.profiles.active}") private String activeProfile;

Here, our activeProfile variable will contain the name of the profile that is currently active, and if there are several, it'll contain their names separated by a comma.

However, we should consider what would happen if there is no active profile at all. With our code above, the absence of an active profile would prevent the application context from being created. This would result in an IllegalArgumentException owing to the missing placeholder for injecting into the variable.

In order to avoid this, we can define a default value:

@Value("${spring.profiles.active:}") private String activeProfile;

Now, if no profiles are active, our activeProfile will just contain an empty string.

And if we want to access the list of them just like in the previous example, we can do it by splitting the activeProfile variable:

public class ProfileManager { @Value("${spring.profiles.active:}") private String activeProfiles; public String getActiveProfiles() { for (String profileName : activeProfiles.split(",")) { System.out.println("Currently active profile - " + profileName); } } }

7. Example: Separate Data Source Configurations Using Profiles

Now that the basics are out of the way, let's take a look at a real example.

Consider a scenario where we have to maintain the data source configuration for both the development and production environments.

Let's create a common interface DatasourceConfig that needs to be implemented by both data source implementations:

public interface DatasourceConfig { public void setup(); }

Following is the configuration for the development environment:

@Component @Profile("dev") public class DevDatasourceConfig implements DatasourceConfig { @Override public void setup() { System.out.println("Setting up datasource for DEV environment. "); } }

And configuration for the production environment:

@Component @Profile("production") public class ProductionDatasourceConfig implements DatasourceConfig { @Override public void setup() { System.out.println("Setting up datasource for PRODUCTION environment. "); } }

Now let's create a test and inject our DatasourceConfig interface; depending on the active profile, Spring will inject DevDatasourceConfig or ProductionDatasourceConfig bean:

public class SpringProfilesWithMavenPropertiesIntegrationTest { @Autowired DatasourceConfig datasourceConfig; public void setupDatasource() { datasourceConfig.setup(); } }

When the dev profile is active, Spring injects DevDatasourceConfig object, and when calling then setup() method, the following is the output:

Setting up datasource for DEV environment.

8. Profiles in Spring Boot

Spring Boot supports all the profile configuration outlined so far, with a few additional features.

The initialization parameter spring.profiles.active, introduced in Section 4, can also be set up as a property in Spring Boot to define currently active profiles. This is a standard property that Spring Boot will pick up automatically:

spring.profiles.active=dev

To set profiles programmatically, we can also use the SpringApplication class:

SpringApplication.setAdditionalProfiles("dev");

To set profiles using Maven in Spring Boot, we can specify profile names under spring-boot-maven-plugin in pom.xml:

  org.springframework.boot spring-boot-maven-plugin   dev    ... 

and execute the Spring Boot-specific Maven goal:

mvn spring-boot:run

But the most important profiles-related feature that Spring Boot brings is profile-specific properties files. These have to be named in the format application-{profile}.properties.

Spring Boot will automatically load the properties in an application.properties file for all profiles, and the ones in profile-specific .properties files only for the specified profile.

For example, we can configure different data sources for dev and production profiles by using two files named application-dev.properties and application-production.properties:

In the application-production.properties file, we can set up a MySql data source:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/db spring.datasource.username=root spring.datasource.password=root

Then we can configure the same properties for the dev profile in the application-dev.properties file, to use an in-memory H2 database:

spring.datasource.driver-class-name=org.h2.Driver spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 spring.datasource.username=sa spring.datasource.password=sa

In this way, we can easily provide different configurations for different environments.

9. Conclusion

В тази статия обсъдихме как да дефинираме профил в боб и как след това да активираме правилните профили в нашето приложение.

И накрая, ние потвърдихме нашето разбиране за профилите с прост, но реален пример.

Прилагането на този урок може да бъде намерено в проекта GitHub.