Why Spring
- Popular framework for building Enterprise applications
- Outsourcing construction and management of Objects
Spring Container
- Primary Functions
- Create and manage objects(Inversion of control)
- Inject Objects dependencies (Dependency Injection)
- Constructor injection & Setter injection
- Configuring Spring Container
- XML configuraiton file-> applicationContext.xml
- Java annotations
- Java source code
- Development process
- Configure your spring beans
- Create Spring Container
- ClassPathXmlApplicationContext
- Retrieve beans from container
- Default Scope: Singleton
- Prototype - new object for each request
- Request
- Session
- globa-session
Bean LifeCycle methods
- Bean container started -> Bean instatiated -> dependencies injected -> Internal spring processing -> customer init method
- define init method in xml using <init-method=""> as part of bean definition
- define destroy method in xml using <destroy-method=""> as part of bean definition
- Automatically register beans in spring container based on special annotations
- Steps
- Enable component scanning in spring config file and specify base package
- add @Component annotation to your java class
- @Component("beanid")
- Dependency injection
- @Autowired
- Constructor injection, Setter injection, Field injection
- @Qualifier to specify which exact bean when there exists multiple implemntations
Scope Annotations
- Lifecycle
- bean initialization, bean destruction using @PostContruct & @PreDestroy
- @PostConstruct will execute after constructor & dependency injection
- @PreDestroy just before bean is destroyed
- how long it lives
- how many instances
- how is bean shared
@scope("singleton") , @scope("prototype"), @scope("singleton"), @scope("singleton")
Configuration with Java Code
- Create java class(MyConfig.java) with annotation @Configuration
- add @ComponentScan annotation OR create method with @Bean annotation and create and return bean objects
- In main method, read configuration class
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext("MyConfig.class"); - retrieve beans using method names.
- Provide following annotation on spring config class
- @PropertySource("classpath:source.properties")
- access values with
- @Value("${foo.team}")
Spring MVC
- Components
- UI Pages
- collection of spring beans(controllers, services etc)
- spring config(xml, annotations or Java)
- Front controller known as dispatcher servlet
- Controller contains business logic
- Model contains data
- View Template with jsp+jstl
- Configuration
- WEB-INF/web.xml
- configure dispatcher servlet & url mappings
- WEB-INF/spring-mvc-demo-servlet.xml
- support for component scanning, view resolver, conversion, validation
- Development Process
- Controller Class -> @Controller inherits Component
- Controller Method
- add Request Mapping
- return viewName
- Form Tags and Data binding
- <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
Hibernate
- Setting up Hybernate
- Eclipse->Java project
- Create lib folder and copy the required jars
- Add lib jars to project build path
- Test jdbc connection
- main(){
Connection conn = DriverManager.getConnection(url,user,pwd); - Hibernate configuration
- config file
- create hibernate.cfg.xml in src directory
- Annotate java class
- @Entity
@Table(name="anyname")
@ID
@Column(name="anyname") - perform db operations
- SessionFactory
- Reads hibernate config file
- creates session objects
- Heavy-weight object
- only create once in your app
- SessionFactory factory = new Configuration().configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class.buildSessionFacory() - Session
- Wraps a jdbc connection
- Main object used to save/retrieve objects
- short-lived object
- Retrieved from session factory
- Session session = factory.getCurrentsession();
- session.beginTransaction()
- session.save(object)
- session.getTransaction().commit();
- Reading Objects
- Student std = session.get(Student.class, id);
- session.createQuery("from Student s where s.lastName='x').getResultList()
- @Repository
- DAO Implementations
- Provides translation for any jdbc exceptions
- AOP(Aspect-Oriented Programming)
- logging before start of the DAO methods and also all layers.
- add security to methods
- Issues
- Code Tangling
- Code Scattering
- AOP
- Programming based on aspect
- Aspect encapsulates cross-cutting logic/concerns
- This is also called infrastructure code
- Can be reused at multiple places
- Proxy design pattern
- Benefits
- code is resided in single place
- reuse
- Business code is cleaner
- Configurable
- No change to main appln code
- Usecases
- Logging
- Exception handlig
- API management
- Disadvantage
- minor perf
- too many aspects- app flow is hard to follow
- Terminology
- Aspect - Module of code for cross-cutting concerns
- Advice- What action is taken and when to apply
- Joint Point-When to apply code during program execution
- Pointcut - A predicate expression for where advice should be applied
- Advice types
- Before- before method
- After- after method
- After returning advice- after method in success case
- after throwing advice - exception case
- Around - before and after
- Weaving
- Connecting aspects to target objects to create an adviced object
- Types
- compile time, run time,
- Frameworkds
- Srping AOP(runtime weaving), AspectJ
- Development process
- Create Target Object/class
- Spring Java config
- @EnableAspectJAutoProxy
- Create an Aspect with @Before advice
- @Aspect -> class level annotation
- @Before("execution)public void addAccount())") -> point cut expression
- Point Cuts
- Execution pointcut
- Config class with any name and following annotations & Bean(method) for viewResolver
- @Configuration
@EnableWebMvc
@ComponentScan(basepackages="") - SpringDispatchServlet
- AbstractAnnotationConfigDispatcherServeletInitializer to replace web.xml
- overried following classes
- getRootConfigClasses
getServletConfigClasses
getServletMappings - Basic security
- security initializer- class extending AbstractSecurityWebApplicationInitializer
to register securitynfilters - spring security configuration extends WebSecurityConfigureAdapter with following annotations
- @Configuration
@EnableWebSecurity - override configure(AuthenticationManagerBuilder) method
- add users and pwd details for inmemory authenticator
- AbstractSecurityWebApplicationInitializer -> to register security filters
- Add users and pwd
- Restrict access by roles
- antMatchers("path to match").hasRole("role name")
- antMatchers("path to match").hasAnyRole(<list of roles)
Spring Rest
- Json to Java pojo
- Jackson Object mapper
- mapper.readValue & mapper.writeValue are methods to be used
- Exception Handling
- define a pojo for exception response
- Create Customexception extends RuntimeException
- Add Exception handler method with ExceptionHandler annotation
- return responseEntity with pojo for Exception response
- Global Exception Handling
- @ControllerAdvice - similar to filter/interceptor
- API design
- Who will user, how will they use
- Identify main resources/Entiry
Spring Boot
- Spring Initializer
- Has embedded HTTP server. Tomcat, Jetty, Undertow
- No xml and java configuration required
- @SpringBootApplication
- Enables Auto configuration, component scanning, Additional configuration
- Project Structure
- mvnw -> maven wrapper files
- They download mvn incase system doesn't have it
- pom.xml
- Spring-boot-starter-web includes
- spring-web
- spring-webmvc
- hibernate-validator
- tomcat
- json
- application.properties
- Spring by default loads the properties from this file
- Values can be accessed using @Value(${propertyname}) - injection
- Spring boot will load static files from /static directory by default
- Auto configuration for template engines line Thymeleaf
- Starter parent
- dependency management version
- spring boot mvn plugin
- default properties like java version and so
Springboot dev tools
- add following dependency to pom for auto restart appln when code changes done
<dependency>
<groupId> org.springframework.boot
<artifactId>spring-boot-devtools
Springboot Acutator
- exposes end points for metrics /health, /info, /beans, /mappings
<dependency>
<groupId> org.springframework.boot
<artifactId>spring-boot-starter-actuator - application.properties
- info.app.name
- info.app.description
- info.app.version
- management.endpoints.web.exposure.include=*
SpringJPA
- Hibernate is default implementation of JPA
- EntityManager is similar to Hibernate SessionFactory. It can serve as wrapper of Hibernate session object
- Version1- Use EntityManager but leverage native Hibernate api
- Version2-Use EntityManager and Standard JPA api
- Version3-SpringData JPA
SpringData JPA-> JPARepository
- SpringData JPA provides a interface JPARepository
- Extend JPARepository
- Use Respository in your code
- eg: public interface EmployeeRepository extends JPARepository<Employee, Integer>{
SpringDataRest
- Add Spring Data Rest to your pom
-
H2 DB -> https://www.youtube.com/watch?v=9ME94z46fsU
- Dependencies
- H2 Database
- Spring Data JPA
- Spring web
- application.properties
- spring.h2.console.enabled=true
- spring.h2.console.path=/h2
- spring.datasource.url=jdbc:h2:mem:memdb; DB_CLOSE_DELAY=-1
OR spring.datasource.url=jdbc:h2:file:/home/vdesu/apps
spring.jpa.hibernate.ddl-auto=update - spring.datasource.driverClassName=org.h2.Driver
- spring.datasource.username=sa
- spring.datasource.password=
- Create Entity Person
- PrimaryKey
- @Id
- @GeneratedValue(strategy=GenerationType.AUTO)
- Create Repository
- @Repository
public interface PersonRepository extends CrudRepository<Person, Long>{} - main()
- ConfigurableApplicationContext ctx = SpringApplication.run(...class,args);
PersonRepository repository = ctx.getBean(PersonRepository.class)
Person p= new Person(1,"a","b");
repository.save(p);
No comments:
Post a Comment