Spring详细内容En(1)

怼烎@ 2023-09-24 18:25 148阅读 0赞

1.Spring

  • It was developed by Rod Johnson in 2003.
  • Spring framework makes the easy development of JavaEE application.

1)Spring Framework

  • Spring is a lightweight framework.
  • It can be thought of as a framework of frameworks because it provides support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF, etc.
  • The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM, WEB MVC etc.

2)Inversion Of Control (IOC) and Dependency Injection

  • These are the design patterns that are used to remove dependency from the programming code.
  • They make the code easier to test and maintain.

    class Employee{

    1. Address address;
    2. Employee(){
    3. address=new Address();
    4. }

    }

there is dependency between the Employee and Address (tight coupling).

  1. class Employee{
  2. Address address;
  3. Employee(Address address){
  4. this.address=address;
  5. }
  6. }
  • IOC makes the code loosely coupled.
  • In such case, there is no need to modify the code if our logic is moved to new environment.
  • In Spring framework, IOC container is responsible to inject the dependency.
  • We provide metadata to the IOC container either by XML fileorannotation.

Advantage of Dependency Injection

  • makes the codeloosely coupled so easy to maintain
  • makes the code easy to test

3) Advantages of Spring Framework

1) Predefined Templates

  • Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies.
  • So there is no need to write too much code.
  • It hides the basic steps of these technologies.

2)Loose Coupling

  • The Spring applications are loosely coupled because of dependency injection.

3)Easy to test

  • The Dependency Injection makes easier to test the application.
  • The EJB or Struts application require server to run the application but Spring framework doesn't require server.

4)Lightweight

  • Spring framework islightweightbecause of its POJO implementation.
  • The Spring Framework doesn’t force the programmer to inherit any class or implement any interface. That is why it is said non-invasive.

5)Fast Development

  • The Dependency Injection feature of Spring Framework and it support to various frameworks makes the easy development of JavaEE application.

6)Powerful abstraction

  • It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA.

7)Declarative support

  • It provides declarative support for caching, validation, transactions and formatting.

2.Spring Modules

  • The Spring framework comprises of many modules such as core, beans, context, expression language, AOP, Aspects, Instrumentation, JDBC, ORM, OXM, JMS, Transaction,Web,Servlet, Struts etc.
  • These modules are grouped into Test, Core Container, AOP, Aspects, Instrumentation, Data Access / Integration, Web (MVC / Remoting)as displayed in the following diagram.
    在这里插入图片描述

1)Test

This layer provides support of testing with JUnitand TestNG.

2) Spring Core Container

The Spring Core container contains core, beans, context and expression language (EL)modules.

Core and Beans

These modules provideIOC and Dependency Injectionfeatures.

Context

This module supports internationalization (I18N), EJB, JMS, Basic Remoting.

Expression Language

  • It is an extension to the EL defined in JSP.
  • It provides support to setting and getting property values, method invocation, accessing collections and indexers, named variables, logical and arithmetic operators, retrieval of objects by name etc.

3)AOP, Aspects and Instrumentation

  • These modules support aspect oriented programmingimplementation where you can use Advices, Pointcuts etc. to decouple the code.
  • The aspects module provides support to integration with AspectJ.
  • The instrumentation module provides support to class instrumentation and classloader implementations.

4)Data Access / Integration

  • this group comprises of JDBC, ORM, OXM, JMS and Transaction modules.
  • These modules basically provide support to interact with the database.

5)Web

  • This group comprises of Web, Web-Servlet, Web-Struts and Web-Portlet.
  • These modules provide support to create web application.

3.Spring application

Step

  1. create the java project
  2. add spring capabilities
  3. create the class
  4. create the xml file to provide the values
  5. create the test class

1) Create the Java Project

Go to File menu - New - project - Java Project. Write the project name e.g. firstspring - Finish. Now the java project is created.

2) Add spring jar files

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>heima_datastuct</artifactId>
  7. <groupId>org.example</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>spring_01</artifactId>
  12. <properties>
  13. <maven.compiler.source>8</maven.compiler.source>
  14. <maven.compiler.target>8</maven.compiler.target>
  15. </properties>
  16. <!--导入spring的context坐标,context依赖core、beans、expression-->
  17. <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
  18. <dependencies>
  19. <dependency>
  20. <groupId>org.springframework</groupId>
  21. <artifactId>spring-core</artifactId>
  22. <version>5.3.25</version>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework</groupId>
  26. <artifactId>spring-beans</artifactId>
  27. <version>5.3.23</version>
  28. <scope>compile</scope>
  29. </dependency>
  30. </dependencies>

3) Create Java class

  1. package com.amy;
  2. /**
  3. * @author: Amy
  4. * @create: 2023-02-14 14:32
  5. **/
  6. public class Student {
  7. private String name;
  8. public String getName() {
  9. return name;
  10. }
  11. public void setName(String name) {
  12. this.name = name;
  13. }
  14. public void displayInfo(){
  15. System.out.println("Hello: "+name);
  16. }
  17. }
  • This is simple bean class, containing only one property name with its getters and setters method.
  • This class contains one extra method named displayInfo() that prints the student name by the hello message.

4) Create the xml file

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:p="http://www.springframework.org/schema/p"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  8. <bean id="student" class="com.amy.Student">
  9. <property name="name" value="Amy"></property>
  10. </bean>
  11. </beans>
  • The bean element is used to define the bean for the given class.
  • The property subelement of bean specifies the property of the Student class named name.
  • The value specified in the property element will be set in the Student class object by the IOC container.

5) Create the test class

  1. package com.amy;
  2. import org.springframework.beans.factory.BeanFactory;
  3. import org.springframework.beans.factory.xml.XmlBeanFactory;
  4. import org.springframework.core.io.ClassPathResource;
  5. import org.springframework.core.io.Resource;
  6. /**
  7. * @author: Amy
  8. * @create: 2023-02-14 14:39
  9. **/
  10. public class Test {
  11. public static void main(String[] args) {
  12. Resource resource = new ClassPathResource("applicationContext.xml");
  13. BeanFactory factory = new XmlBeanFactory(resource);
  14. Student student = (Student) factory.getBean("student");
  15. student.displayInfo();;
  16. }
  17. }
  • The Resource object represents the information of applicationContext.xml file.
  • The Resource is the interface and the ClassPathResource is the implementation class of the Reource interface.
  • The BeanFactory is responsible to return the bean.
  • The XmlBeanFactory is the implementation class of the BeanFactory.
  • There are many methods in the BeanFactory interface.
  • One method is getBean(), which returns the object of the associated class.
  1. Hello: Amy

4. IoC Container

  • The IoC container is responsible to instantiate, configure and assemble the objects.
  • The IoC container gets informations from theXML file and works accordingly.
  • The main tasks performed by IoC container are:

    • to instantiate the application class
    • to configure the object
    • to assemble the dependencies between the objects
  • There are two types of IoC containers. They are:

    1. BeanFactory
    2. ApplicationContext

1)Difference between BeanFactory and the ApplicationContext

  • The org.springframework.beans.factory.BeanFactoryand the org.springframework.context.ApplicationContext interfaces acts as the IoC container.
  • The ApplicationContext interface is built on top of the BeanFactory interface.
  • It adds some extra functionality than BeanFactory such as simple integration with Spring's AOP, message resource handling (for I18N), event propagation, application layer specific context (e.g. WebApplicationContext)for web application.
  • So it is better to use ApplicationContext than BeanFactory.

2)Using BeanFactory

  • The XmlBeanFactory is the implementation class for the BeanFactory interface.
  • To use the BeanFactory, we need to create the instance of XmlBeanFactory class

    Resource resource=new ClassPathResource(“applicationContext.xml”);
    BeanFactory factory=new XmlBeanFactory(resource);

  • the constructor of XmlBeanFactory class receives the Resource object so we need to pass the resource object to create the object of BeanFactory.
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

3)Using ApplicationContext

  • The ClassPathXmlApplicationContext class is the implementation class of ApplicationContext interface.
  • We need to instantiate the ClassPathXmlApplicationContext class to use the ApplicationContext

    ApplicationContext context = new ClassPathXmlApplicationContext(“applicationContext.xml”);

  • The constructor of ClassPathXmlApplicationContextclass receives string, so we can pass the name of the xml file to create the instance of ApplicationContext.

5. Dependency Injection in Spring

  • Dependency Injection (DI)is a design pattern that removes the dependency from the programming code so that it can be easy to manage and test the application.
  • Dependency Injection makes our programming code loosely coupled.

1)Dependency Lookup

  • The Dependency Lookup is an approach where we get the resource after demand.
    A obj = new AImpl();
  • In such way, we get the resource(instance of A class) directly by new keyword. Another way is factory method:
    A obj = A.getA();
  • This way, we get the resource (instance of A class) by calling the static factory method getA().
  • Alternatively, we can get the resource by JNDI (Java Naming Directory Interface) as:

    Context ctx = new InitialContext();
    Context environmentCtx = (Context) ctx.lookup(“java:comp/env”);
    A obj = (A)environmentCtx.lookup(“A”);

Problems of Dependency Lookup

  • There are mainly two problems of dependency lookup.

    • tight coupling The dependency lookup approach makes the code tightly coupled. If resource is changed, we need to perform a lot of modification in the code.
    • Not easy for testing This approach creates a lot of problems while testing the application especially in black box testing.

2)Dependency Injection

  • The Dependency Injection is a design pattern thatremoves the dependency of the programs.
  • In such case we provide the information from the external source such as XML file.
  • It makes our code loosely coupled and easier for testing.

    class Employee{

    1. Address address;
    2. Employee(Address address){
    3. this.address=address;
    4. }
    5. public void setAddress(Address address){
    6. this.address=address;
    7. }

    }

  • In such case, instance of Address class is provided by external souce such as XML file either by constructor or setter method.

Two ways to perform Dependency Injection in Spring framework

  • We can inject the dependency by constructor.
  • The <constructor-arg>subelement of is used for constructor injection.

(1)By Constructor

  1. public class Student {
  2. private String name;
  3. public Student(String name) {
  4. this.name =name;
  5. }
  6. public void displayInfo(){
  7. System.out.println("Hello: "+name);
  8. }
  9. }
  10. <?xml version="1.0" encoding="UTF-8"?>
  11. <beans
  12. xmlns="http://www.springframework.org/schema/beans"
  13. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  14. xmlns:p="http://www.springframework.org/schema/p"
  15. xsi:schemaLocation="http://www.springframework.org/schema/beans
  16. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  17. <bean id="student" class="com.amy.Student">
  18. <constructor-arg value="Amy" type="String"></constructor-arg>
  19. </bean>
  20. </beans>
  • We are providing the information into the bean by this file.
  • The constructor-arg element invokes the constructor.
  • In such case, parameterized constructor of String type will be invoked.
  • The value attribute of constructor-arg element will assign the specified value.
  • The type attribute specifies that String parameter constructor will be invoked.
  1. public class Test {
  2. public static void main(String[] args) {
  3. Resource resource = new ClassPathResource("applicationContext.xml");
  4. BeanFactory factory = new XmlBeanFactory(resource);
  5. Student student = (Student) factory.getBean("student");
  6. student.displayInfo();;
  7. }
  8. }
  9. Hello: Amy
Injecting string-based values
  • If you don’t specify the type attribute in the constructor-arg element, by default string type constructor will be invoked.



(2)By Setter method

  • We can inject the dependency by setter method also.
  • The subelement of is used for setter injection.

    public class Employee {

    1. private int id;
    2. private String name;
    3. private String city;
    4. public int getId() {
    5. return id;
    6. }
    7. public void setId(int id) {
    8. this.id = id;
    9. }
    10. public String getName() {
    11. return name;
    12. }
    13. public void setName(String name) {
    14. this.name = name;
    15. }
    16. public String getCity() {
    17. return city;
    18. }
    19. public void setCity(String city) {
    20. this.city = city;
    21. }
    22. public void display(){
    23. System.out.println(id+" "+name+" "+city);
    24. }

    }

    <?xml version=”1.0” encoding=”UTF-8”?>












    public class Test1 {

    1. public static void main(String[] args) {
    2. Resource resource = new ClassPathResource("applicationContext.xml");
    3. BeanFactory factory = new XmlBeanFactory(resource);
    4. Employee employee = (Employee) factory.getBean("employee");
    5. employee.display();
    6. }

    }

    1 Amy ShangHai

发表评论

表情:
评论列表 (有 0 条评论,148人围观)

还没有评论,来说两句吧...

相关阅读