compile("org.springframework.boot:spring-boot-starter-security")
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired UserRepository userRepository; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/").access("hasRole(ADMIN)") .antMatchers("/**").permitAll() .and() .formLogin() .loginPage("/login") .failureUrl("/login?error=true"); } @Override protected void configure( AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(new UserDetailsService() { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return userRepository.findUserName(username); } }); } }
$ java -jar myapp-0.0.1-SNAPSHOT.jar --spring.main.show-banner=false
spring.main.show-banner=false
spring: main: show-banner: false
$ export spring_main_show_banner=false
$ java -jar myapp-0.0.1-SNAPSHOT.jar --spring.thymeleaf.cache=false
spring: thymeleaf: cache: false
$ export spring_thymeleaf_cache=false
$ java -jar myapp-0.0.1-SNAPSHOT.jar --server.port=8181
server: port: 8000
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency>
configurations { all*.exclude group:'org.springframework.boot', module:'spring-boot-starter-logging' }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j</artifactId> </dependency>
compile("org.springframework.boot:spring-boot-starter-log4j")
<configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern> %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n </pattern> </encoder> </appender> <logger name="root" level="INFO"/> <root level="INFO"> <appender-ref ref="STDOUT" /> </root> </configuration>
logging: level: root: WARN org: springframework: security: DEBUG
Now suppose that you want to write the log entries to a file named MyApp.log at /opt/logs/. The logging.path and logging.file properties can help with that:
logging: path: /opt/logs/ file: MyApp.log level: root: WARN org: springframework: security: DEBUG
By default, the log files will rotate once they hit 10 megabytes in size.
application.properties:
logging.path=/opt/logs/ logging.file=MyApp.log logging.level.root=WARN logging.level.root.org.springframework.>You can also change name of logger configuration file name i.e. you can change name of file logback.xml to log-config.xml by setting the property logging.config in property file or YML file.
logging: config: classpath:log-config.xml4. CONFIGURING A DATA SOURCE
application.yml: if you’re using a MySQL database, your application.yml file might look like thisspring: datasource: url: jdbc:mysql://localhost/dojdb username: root password: rootSpecify driver name for database with property spring.datasource
.driver-class-name property as followsspring: datasource: url: jdbc:mysql://localhost/dojdb username: root password: root driver-class-name: com.mysql.jdbc.DriverUsing JNDI for DataSource:
By using property spring.datasource.jndi-namespring: datasource: jndi-name: java:/comp/env/jdbc/dojDBDSType-safe Configuration Properties
If you are working with multiple properties or your data is hierarchical in nature then sometimes it may be problem in configuration properties. Spring Boot provides an alternative method of working with properties that allows strongly typed beans to govern and validate the configuration of your application.For example:
@Component @ConfigurationProperties(prefix="database") public class DatabaseSettings { private String dbname; private String dburl; // ... getters and setters }The @EnableConfigurationProperties annotation is automatically applied to your project so that any beans annotated with @ConfigurationProperties will be configured from the Environment properties. The @ConfigurationProperties annotation won’t work unless you’ve enabled it by adding @EnableConfigurationProperties in one of your Spring configuration classes. This style of configuration works particularly well with the SpringApplication external YAML configuration:
application.ymldatabase: dbname: dojdb dburl: jdbc:mysql//192.168.1.1:3309/dojdb # additional configuration as requiredTo work with @ConfigurationProperties beans you can just inject them in the same way as any other bean.
@Service public class UserService { @Autowired private DatabaseSettings connection; //... @PostConstruct public void openConnection() { Server server = new Server(); this.connection.configure(server); } }It is also possible to shortcut the registration of @ConfigurationProperties bean definitions by simply listing the properties classes directly in the @EnableConfigurationProperties annotation:
@Configuration @EnableConfigurationProperties(DatabaseSettings.class) public class DBConfiguration { }Using @ConfigurationProperties for outside beans:
We can use @ConfigurationProperties for beans which either outside from the application or not in your control. Let‘s see below@ConfigurationProperties(prefix = "foo") @Bean public FooComponent fooComponent() { ... }Any property defined with the foo prefix will be mapped onto that FooComponent bean in a similar manner as the DatabaseSettings example above.
Note: Biding Property in Spring Boot
It’s also worth noting that Spring Boot’s property resolver is clever enough to treat camel-cased properties as interchangeable with similarly named properties with hyphens or underscores. In other words, a property named database.dbName is equivalent to both database.db_name and database.db-name. And also DATABASE_DB_NAME as environment variable in OS.@ConfigurationProperties Validation
Spring Boot will attempt to validate external configuration, by default using JSR-303 (if it is on the classpath). You can simply add JSR-303 javax.validation constraint annotations to your @ConfigurationProperties class:@Component @ConfigurationProperties(prefix="database") public class DatabaseSettings { @NotNull private String dbName; @NotNull private String dbUrl; // ... getters and setters }Configuring with profiles
When applications are deployed to different runtime environments, there are usually some configuration details that will differ. The details of a database connection, for instance, are likely different in a development environment than in a quality assurance environment, and different still in a production environment.@Configuration @Profile("production") public class ProductionConfiguration { // ... }The @Profile annotation used here requires that the “production” profile be active at runtime for this configuration to be applied. If the “production” profile isn’t active, this configuration will be ignored and applied any default auto configuration.
Activate profiles:
Profiles can be activated by setting the spring.profiles.active property using any of the means available for setting any other configuration property. For example, you could activate the “production” profile by running the application at the command line like this:$ java -jar MyApp-0.0.1-SNAPSHOT.jar -- spring.profiles.active=productionOr you can add the spring.profiles.active property to application.yml:
spring: profiles: active: productionProfile-specific properties:
If you’re using application.properties to express configuration properties, you can provide profile-specific properties by creating additional properties files named with the pattern “application-{profile}.properties”. Profile-specific properties are loaded from the same locations as standard application.properties, with profile-specific files always overriding the non-specific ones irrespective of whether the profile-specific files are inside or outside your packaged jar.For Example the development configuration would be in a file named application-development.properties and contain properties for verbose, console written logging:
logging.level.root=DEBUGBut for production, application-production.properties would configure logging to be at WARN level and higher and to write to a log file:
logging.path=/opt/logs/ logging.file=MyApp.log logging.level.root=WARNMulti-profile YAML documents:
You can specify multiple profile-specific YAML documents in a single file by using a spring.profiles key to indicate when the document applies. For example:logging: level: root: INFO --- spring: profiles: development logging: level: root: DEBUG --- spring: profiles: production logging: path: /opt/ file: MyApp.log level: root: WARNAs you can see, this application.yml file is divided into three sections by a set of triple hyphens (---). The second and third sections each specify a value for spring .profiles. This property indicates which profile each section’s properties apply to.
The properties defined in the middle section apply to development because it sets spring.profiles to “development”. Similarly, the last section has spring.profiles set to “production”, making it applicable when the “production” profile is active.
The first section, on the other hand, doesn’t specify a value for spring.profiles. Therefore, its properties are common to all profiles or are defaults if the active profile doesn’t otherwise have the properties set.
Customizing error pages
Spring Boot offers this “whitelabel” error page by default as part of auto-configuration. The default error handler that’s auto-configured by Spring Boot looks for a view whose name is “error”. The easiest way to customize the error page is to create a custom view that will resolve for a view named “error”.Ultimately this depends on the view resolvers in place when the error view is being resolved. This includes
Summary
Spring Boot Auto configuration do almost configuration for your application. When autoconfiguration doesn’t fit your needs, Spring Boot allows you to override and fine-tune the configuration it provides.
Happy Spring Boot Learning!!!
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…