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
- @TestPropertySource annotations on your tests.
- Command line arguments.
- Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property)
- ServletConfig init parameters.
- ServletContext init parameters.
- JNDI attributes from java:comp/env.
- Java System properties (System.getProperties()).
- OS environment variables.
- A RandomValuePropertySource that only has properties in random.*.
- Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants)
- Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants)
- Application properties outside of your packaged jar (application.properties and YAML variants).
- Application properties packaged inside your jar (application.properties and YAML variants).
- @PropertySource annotations on your @Configuration classes.
- Default properties (specified using SpringApplication.setDefaultProperties)
- Externally, in a /config subdirectory of the directory from which the application is run
- Externally, in the directory from which the application is run
- Internally, in a package named “config”
- Internally, at the root of the classpath
$ java -jar myapp-0.0.1-SNAPSHOT.jar --spring.thymeleaf.cache=false
spring: thymeleaf: cache: false
$ export spring_thymeleaf_cache=false
- spring.freemarker.cache (Freemarker)
- spring.groovy.template.cache (Groovy templates)
- spring.velocity.cache (Velocity)
$ 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>
application.yml:
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.security=DEBUG
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.xml
4. CONFIGURING A DATA SOURCE
application.yml: if you’re using a MySQL database, your application.yml file might look like this
spring: datasource: url: jdbc:mysql://localhost/dojdb username: root password: root
Specify driver name for database with property spring.datasource
.driver-class-name property as follows
spring: datasource: url: jdbc:mysql://localhost/dojdb username: root password: root driver-class-name: com.mysql.jdbc.Driver
Using JNDI for DataSource:
By using property spring.datasource.jndi-name
spring: datasource: jndi-name: java:/comp/env/jdbc/dojDBDS
Type-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.yml
database: dbname: dojdb dburl: jdbc:mysql//192.168.1.1:3309/dojdb # additional configuration as required
To 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=production
Or you can add the spring.profiles.active property to application.yml:
spring: profiles: active: production
Profile-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=DEBUG
But 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=WARN
Multi-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: WARN
As 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
- Any bean that implements Spring’s View interface and has a bean ID of “error” (resolved by Spring’s BeanNameViewResolver)
- A Thymeleaf template named “error.html” if Thymeleaf is configured
- A FreeMarker template named “error.ftl” if FreeMarker is configured
- A Velocity template named “error.vm” if Velocity is configured
- A JSP template named “error.jsp” if using JSP views
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!!!
- Spring Boot Interview Questions and Answers
- Introduction to Spring Boot
- Essentials and Key Components of Spring Boot
- Spring Boot CLI Installation and Hello World Example
- Spring Boot Initializr Web Interface
- Spring Boot Initializr With IDEs
- Spring Boot Initializr With Spring Boot CLI
- Installing Spring Boot
- Developing your first Spring Boot application
- Logging Configuration in Spring Boot
- Spring Boot and Spring MVC
- Working with SQL Databases and Spring Boot
- MySQL Configurations
- Spring Data JPA using Spring Boot Application
- Spring Boot with NoSQL technologies
- Spring Cache Tutorial
- Spring Security Tutorial with Spring Boot
- Spring Boot and MongoDB in REST Application
- Complete Guide for Spring Boot Actuator
- Microservices with Spring Boot