Spring source code: a preliminary understanding of the construction and use of spring projects

Official website address: https://github.com/spring-projects/spring-framework
Chinese documents: https://github.com/DocsHome/spring-docs/blob/master/SUMMARY.md
Family list: https://spring.io/projects

1, First spring project (Xml mode)

1. Import pom file

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.5.RELEASE</version>
</dependency>

2. Add bean corresponding class

public class TestService {
    public void sayHello() {
        System.out.println("Hello");
    }
}

3. Add services under resources xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="testService" class="service.TestService">
    </bean>
</beans>

4. Write main method

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("services.xml");
    TestService bean = context.getBean(TestService.class);
    bean.sayHello();
}

5. View the running effect

Hello
Process finished with exit code 0

2, The first spring project (JavaConfig mode)

1. Import pom file

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.5.RELEASE</version>
</dependency>

2. Add bean corresponding class

public class ConfigTestService {
    public void sayHello() {
        System.out.println("config:Hello");
    }
}

3. Add config corresponding class

@Configuration
public class MyConfig {
    @Bean
    public ConfigTestService configTestService() {
        return new ConfigTestService();
    }
}

4. Write main method

public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
    ConfigTestService bean = context.getBean(ConfigTestService.class);
    bean.sayHello();
}

5. View the running effect

config:Hello
Process finished with exit code 0

3, The first spring project (JavaConfig+xml combination)

1. Modify main method

public static void main(String[] args) {
   AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
   new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml");
   context.register(MyConfig.class);
   context.refresh();
   ConfigTestService bean = context.getBean(ConfigTestService.class);
   bean.sayHello();
   TestService bean2 = context.getBean(TestService.class);
   bean2.sayHello();
}

2. View the running effect

config:Hello
 Hello

Process finished with exit code 0

4, Use of different functions of Spring

1. Alias bean s

xml mode:

<alias name="testService" alias="toName"/>

javaConfig mode:

@Bean(name = {"a", "b", "c"})

2. Static factory

<bean id="clientService" class="service.ClientService" factory-method="createInstance"/>

3. Example factory

<bean id="serviceLocator" class="examples.DefaultServiceLocator">
</bean>

<bean id="clientService"  factory-bean="serviceLocator" factory-method="createClientServiceInstance"/>

4. Dependency injection

4.1 constructor

<bean id="thingOne" class="x.y.ThingOne">
   <constructor-arg ref="thingTwo"/>
   <constructor-arg type="java.lang.String" value="42"/>
</bean>

4.2 setter method

<bean id="exampleBean" class="examples.ExampleBean">
    <!-- setter injection using the nested ref element -->
    <property name="beanOne">
        <ref bean="anotherExampleBean"/>
    </property>

    <!-- setter injection using the neater ref attribute -->
    <property name="beanTwo" ref="yetAnotherBean"/>
    <property name="integerProperty" value="1"/>
</bean>

4.3 dependencies on attribute

Rely on another bean

<bean id="beanOne" class="ExampleBean" depends-on="manager"/>

4.4 lazy loading

<bean id="lazy" class="com.something.ExpensiveToCreateBean" lazy-init="true"/>

4.5 automatic assembly

pattern explain
no (default) do not auto assemble. Bean references must be defined by ref elements. For the deployment of larger projects, it is not recommended to modify the default configuration, because specifying the collaborator can provide better control and clarity. To some extent, it records the structure of the system.
byName Auto assemble by attribute name. Spring finds a bean with the same name as the property that needs to be automatically assembled. For example, if a bean is configured to be assembled by name and contains a property named master (that is, it has a setMaster(...) method), spring will look up the bean definition named master and use it to set properties.
byType If there is only one type of attribute to be automatically assembled in the container, it allows automatic assembly. If there are more than one, a fatal exception is thrown, which means that you cannot use byType auto assembly on the bean. If there is no matching bean, nothing happens (this property is not set).
constructor Similar to byType, but applied to constructor parameters. If no Bean in the container has the same type as the constructor parameter, a fatal error will be raised.

5 scope

Scope describe
singleton (default) each Spring IOC container has a unique instance object.
prototype A Bean definition can create any number of instance objects
request Limit the scope of a single bean definition to the life cycle of a single HTTP request. That is, each HTTP request has its own bean instance, which is created after the definition of a single bean. Only the Web-based Spring ApplicationContext is available.
session Limit the scope of a single bean definition to the life cycle of HTTP Session. Only the Web-based Spring ApplicationContext is available.
application Limit the scope of a single bean definition to the life cycle of ServletContext. Only the Web-based Spring ApplicationContext is available.
websocket Limit the scope of a single bean definition to the life cycle of WebSocket. Only the Web-based Spring ApplicationContext is available.
<bean scope="singleton"/>
<bean scope="prototype"/>
...
@RequestScope
@SessionScope
@ApplicationScope
...

Tags: Java Spring

Posted by nyfael on Mon, 02 May 2022 23:07:48 +0300