Skip to main content

Posts

Showing posts with the label Spring

Spring Core - PropertyPlaceHolderConfigurer example

In this post, we will externalize the properties used in the application in a property file and will use PropertyPlaceHolderConfigurer to resolve the placeholder at application startup time. Java Configuration for PropertyPlaceHolderConfigurer @Configuration public class AppConfig { @Bean public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer(); propertySourcesPlaceholderConfigurer.setLocations(new ClassPathResource("application-db.properties")); //propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true); //propertySourcesPlaceholderConfigurer.setIgnoreResourceNotFound(true); return propertySourcesPlaceholderConfigurer; } } We created object of PropertySourcesPlaceholderConfigurer and set the Locations to search. In this example we used ClassPathResource to resolve the properti

Spring Security: Digest Authentication example

In this post, we will discuss about Digest Authentication with Spring Security. You can also read my previous post on Basic Authentication with Spring Security . What is Digest Authentication? This authentication method makes use of a hashing algorithms to encrypt the password (called password hash) entered by the user before sending it to the server. This, obviously, makes it much safer than the basic authentication method, in which the user’s password travels in plain text (or base64 encoded) that can be easily read by whoever intercepts it. There are many such hashing algorithms in java also, which can prove really effective for password security such as MD5, SHA, BCrypt, SCrypt and PBKDF2WithHmacSHA1 algorithms. Please remember that once this password hash is generated and stored in database, you can not convert it back to original password. Each time user login into application, you have to regenerate password hash again, and match with hash stored in database. So, if user

Spring Security: Basic Authentication example

In this post we will discuss about Basic Authentication and how to use it using Spring Security. BASIC Authentication It’s simplest of all techniques and probably most used as well. You use login/password forms – it’s basic authentication only. You input your username and password and submit the form to server, and application identify you as a user – you are allowed to use the system – else you get error. The main problem with this security implementation is that credentials are propagated in a plain way from the client to the server. Credentials are merely encoded with Base64 in transit, but not encrypted or hashed in any way. This way, any sniffer could read the sent packages over the network. HTTPS is, therefore, typically preferred over or used in conjunction with Basic Authentication which makes the conversation with the web server entirely encrypted. The best part is that nobody can even guess from the outside that Basic Auth is taking place. Let's create a simple S

Spring Boot - Restful webservices with Jersey

In the previous posts, we have created a Spring Boot QuickStart , customized the embedded server and properties and running specific code after spring boot application starts . Now in this post, we will create Restful webservices with Jersey deployed on Undertow as a Spring Boot Application. Adding dependencies in pom.xml We will add spring-boot-starter-parent as parent of our maven based project. The added benefit of this is version management for spring dependencies. <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.0.RELEASE</version> </parent> Adding spring-boot-starter-jersey dependency This will add/ configure the jersey related dependencies. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jersey</artifactId> </dependency> Adding spring-boot-starter-undertow depend

Spring Boot - ApplicationRunner and CommandLineRunner

Spring Boot provides two interfaces CommandLineRunner and ApplicationRunner to run specific piece of code when application is fully started. These interfaces get called just before run() on SpringApplication completes. CommandLineRunner This interface provides access to application arguments as string array. Let's see the example code for more clarity. @Component public class CommandLineAppStartupRunner implements CommandLineRunner { private static final Logger logger = LoggerFactory.getLogger(CommandLineAppStartupRunner.class); @Override public void run(String... args) throws Exception { logger.info("Application started with command-line arguments: {} . \n To kill this application, press Ctrl + C.", Arrays.toString(args)); } } ApplicationRunner ApplicationRunner wraps the raw application arguments and exposes interface ApplicationArguments which have many convinent methods to get arguments like getOptionNames() return all the arguments names

Spring Boot - changing/ configuring default embedded server

In the previous post , we have created a web-based Spring Boot application which uses Embedded Tomcat as the default server running on default port 8080 . Spring Boot supports Tomcat, Undetow and Jetty as embedded servers. Now, we will change and/ or configure the default embedded server and common properties to all the available servers. Spring Boot provides convenient way of configuring dependencies with its starters. For changing the embedded server, we will user its spring-boot-starter-undertow . Adding dependencies <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> </dependency> spring-boot-starter-web comes with Embedded Tomcat. We need to exclude this dependency. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.s

Spring Boot - A quick start

In this post, we will create a simple Spring Boot application which will run on embedded Apache Tomcat. What is Spring Boot? Spring Boot helps in creating stand-alone, production-grade application easily with minimum fuss. It is the opinionated view of Spring framework and other third party libraries which believes in convenient configuration based setup. Let's start building Spring Boot Application. Adding dependencies in pom.xml We will first add spring-boot-starter-parent as parent of our maven based project. <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version> </parent> The benefit of adding spring-boot-starter-parent is that version managing of dependency is easy. You can omit the required version on the dependency. It will pick the one configured the parent pom or from starters pom. Also, it conveniently setup the build r

Spring Core - Bean scopes (Prototype vs Singleton)

In this post, we will discuss about various bean scopes and their differences. Bean scopes There are seven bean scopes Spring supports out of which five are only available if your ApplicationContext is web-aware. # Scope Explanation 1 singleton There will be single object of the bean per Spring IoC Container (Default). 2 prototype Scope beans to any number of object instances. Every time you get object of prototype bean from context, it will be brand new. 3 request Scope of the bean definition mapped to the lifecycle of HTTP Request. This is only available web-aware ApplicationContext . 4 session Scope of the bean definition mapped to the lifecycle of HTTP session. This is only available to web-aware ApplicationContext . 5 globalSession Scope of the bean definition mapped to the lifecycle of HTTP session usually used within Portlet context. This is only available to web-aware ApplicationContext . 6 application Scope of the bean definition mapp

Spring Core - Dependency Injection

What is Dependency Injection? Dependency injection is a process in which objects define their dependencies i.e. other objects they require to work, through a constructor, setter methods, factory methods. The container responsibility is to inject those while creating beans. With Dependency inject in place, we have cleaner code and clear way of decoupling. There are two prominent variants of Dependency Injection. Constructor based Dependency Injection Setter based Dependency Injection Constructor based Dependency Injection When you express your dependencies through constructor arguments and your container invoke your constructor with number of arguments, type of arguments expected by the constructor. Let's jump to one quick example. @Component public class ConstructorBasedFileParser { private Parser parser; @Autowired public ConstructorBasedFileParser(Parser parser) { this.parser = parser; } public void setParser(Parser parser) { this.parser = parser;

Spring Core - @Import annotation

In this post, we will learn about @Import annotation and its usage. You can see my previous post on how to create a simple spring core project. What is @Import annotation and usage? @Import annotation is equivalent to <import/> element in Spring XML configuration. It helps in splitting the single Java based configuration file into small, modular, maintainable and component based configuration. Let's see it with example. @Configuration @Import(value = { DBConfig.class, WelcomeGbConfig.class }) public class HelloGbAppConfig { } In above code snippet, we are importing two different configuration files viz. DBConfig , WelcomeGbConfig in application level configuration file HelloGbAppConfig . The above code is equivalent to Spring XML based configuration below. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/bean

Spring Core - Java configuration example

In this post, we will create a spring context and will register bean via Java configuration file. You can see my previous post on how to create a simple spring core project. What is @Configuration annotation? @Configuration annotation indicates that there is one or more bean methods and spring containers can process to generate bean definitions at runtime. Also, @Bean annotation is used at method level to signifies that this will be registered as bean in spring context. Let's create a quick configuration class. @Configuration public class WelcomeGbConfig { @Bean GreetingService greetingService() { return new GreetingService(); } } Now, we will create spring context as follows. // using try with resources so that this context closes automatically try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( WelcomeGbConfig.class);) { GreetingService greetingService = context.getBean(GreetingService.class); greetingService.gre

Spring Core - A quick start

In this post, we will create a Spring context and will get a bean object from it. What is Spring context? Spring context is also termed as Spring IoC container which is responsible for instantiate, configure and assemble the beans by reading configuration meta data from XML, Java annotations and/ or Java code in configuration files. Technologies used Spring 4.3.6.RELEASE, Maven Compiler 3.6.0 and Java 1.8 We will first create a simple maven project. You can select the maven-archtype-quickstart as archtype. Adding dependencies in pom.xml We will add spring-framework-bom in the dependency management. <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-framework-bom</artifactId> <version>4.3.6.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </depe

Spring 4.3 - New @RequestMapping annotation

Spring 4.3 - @GetMapping, @PostMapping, @PutMapping and @DeleteMapping There are some new improvements in Spring Boot 1.4 and Spring 4.3 which lead to a better readability and some use of annotations, particularly with HTTP request methods. We usually map GET, PUT, POST and DELETE HTTP method in rest controller in the following way. @RestController @RequestMapping ( "/api/employees" ) public class EmployeeController { @RequestMapping public ResponseEntity < List < Employee >> getAll () { return ResponseEntity . ok ( Collections . emptyList ()); } @RequestMapping ( "/{employeeId}" ) public ResponseEntity < Employee > findById ( @PathVariable Long employeeId ) { return ResponseEntity . ok ( EmployeeStub . findById ( employeeId )); } @RequestMapping ( method = RequestMethod . POST ) public ResponseEntity < Employee > addEmployee ( @RequestBody Employee employee ) { return Respons