(3) Spring from entry to soil-quickly get started with Spring and IOC to create objects

HelloSpring

​ If we want to use Spring, we must first import its jar package first. We only need to add the corresponding dependency in the maven configuration file, and the corresponding dependency will be automatically downloaded.

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>

Write code

Write a Hello entity class
public class Hello {
    public String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        System.out.println("set");
        this.str = str;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}
Write a Spring file and name it beans.xml

There are usually two ways to configure metadata:

  • Annotation-based configuration: XML-based configuration metadata configures these beans as
  • Java-based configuration: Use @Bean to use annotated methods in the @Configuration class.

Here is an annotation-based configuration

<?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">

    <!--使用spring来创建对象-->
    <bean id="hello" class="com.zhonghu.pojo.Hello">
    <!--
       value:具体的值
       ref:引用Spring容器中已经创建好的对象。           
    -->
        <property name="str" value="Spring"/>
    </bean>
</beans>

The id here is a string that identifies a single bean definition; class is the type of the Bean and uses the fully qualified class name.

Instantiate the container

The container can be instantiated through the ApplicationContext constructor provided by Spring. It uses one or more parameters to load configuration metadata Classpath from various external resources.

@Test
public void test(){
   //解析beans.xml文件 , 生成管理相应的Bean对象
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   //getBean : 参数即为spring配置文件中bean的id .
   Hello hello = (Hello) context.getBean("hello");
   // Hello hello = context.getBean("hello",Hello.class);
   System.out.println(hello.toString());
}
Results and summary
  • result

image

  • to sum up

    • In the result, we can clearly see that it calls the set method, which means that the set method is the basis for implementing Ioc.
    • Who created the Hello object? ——Created by Spring
    • How are the properties of the Hello object set? ——The attributes of the hello object are implemented by the Spring container.
  • This process is the inversion of control:

    • Control: who controls the creation of objects, traditional applications are created by programmers, after using spring, objects are created by spring
    • Reversal: The program itself does not create objects, but becomes passively accepting objects
  • Dependency injection: is to use the set method to inject

After using this method, we do not need to modify the program, to achieve different operations, only need to modify in the xml configuration file.

The so-called IOC is: objects are created, managed, and assembled by Spring

IOC create object method

Created by no-argument construction method

User.java
public class User {

   private String name;

   public User() {
       System.out.println("user无参构造方法");
  }

   public void setName(String name) {
       this.name = name;
  }

   public void show(){
       System.out.println("name="+ name );
  }

}
beans.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="user" class="com.zhonghu.pojo.User">
        <property name="name" value="zhonghu"/>
    </bean>

</beans>
test
@Test
public void test(){
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   //在执行getBean之前, user已经创建好了 , 通过无参构造
   User user = (User) context.getBean("user");
   //调用对象的方法 .
   user.show();
}
result

image

​ It can be found that before calling the show method, the User object has been initialized through the no-parameter construction. The object is already created when the container is created.

Spring creates an object through parameterless construction, and then uses the set method to inject it.

Its name attribute is a member attribute in the class

Created by a parameterized construction method

UserT.java
public class UserT {

   private String name;

   public UserT(String name) {
       this.name = name;
  }

   public void setName(String name) {
       this.name = name;
  }

   public void show(){
       System.out.println("name="+ name );
  }

}
There are three ways in beans.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="userT" class="com.zhonghu.pojo.UserT">
<!--        name 指参数名-->
        <constructor-arg name="name"value="zhonghu"/>

    </bean>


<!--    第二种根骨index参数下标来设置-->
    <bean id="userT" class="com.zhonghu.pojo.UserT">
<!--     index值构造方法,下标从0开始   -->
        <constructor-arg index="0" value="zhonghu"/>
    </bean>



<!--   第三种 根据参数类型设置 十分不推荐-->
    <bean id="useT"class="com.zhonghu.pojo.UserT">
        <constructor-arg type="java.lang.String" value="zhonghu"/>
    </bean>
</beans>
test
@Test
public void testT(){
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   UserT user = (UserT) context.getBean("userT");
   user.show();
}
to sum up

​ When the configuration file is loaded. The managed objects have been initialized

The name attribute corresponds to the parameter name of the parameter structure

When is the Spring bean instantiated

Use BeanFactory as the factory class

All Beans are initialized when the Bean is used for the first time (lazy loading)

Use ApplicationContext as a factory class
  • If the scope of the bean is singleton, and lazy-init is false (the default is false, so you don’t need to set it), then the Bean will be instantiated when the ApplicationContext starts, and the instantiated Bean will be placed in a map structure cache , The next time you use the Bean, it will be taken directly from the cache
  • If the scope of the bean is singleton and lazy-init is true, then the bean is instantiated when the bean is used for the first time
  • If the scope of the bean is prototype, the instantiation of the bean is instantiated when the bean is used for the first time

Spring configuration

Alias

alias Set alias for bean, you can set multiple aliases at the same time

<!--设置别名:在获取Bean的时候可以使用别名获取-->
<alias name="userT" alias="userNew"/>

Bean configuration

<!--bean就是java对象,由Spring创建和管理-->

<!--
   id 是bean的标识符,要唯一,如果没有配置id,name就是默认标识符
   如果配置id,又配置了name,那么name是别名
   name可以设置多个别名,可以用逗号,分号,空格隔开
   如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象;

class是bean的全限定名=包名+类名
-->
<bean id="hello" name="hello2 h2,h3;h4" class="com.zhonghu.pojo.Hello">
   <property name="name" value="Spring"/>
</bean>

import

Generally used for team development, multiple configuration files can be imported and merged into one.

<import resource="{path}/beans.xml"/>

to sum up

  • How IOC creates objects

    • No parameter construction: its name attribute is a member attribute of the class
    • Parameterized structure: its name attribute corresponds to the parameter name of the parameterized structure
  • When is the Spring Bean initialized

    • Use BeanFactory as the factory class
      • All Beans are initialized when the Bean is used for the first time (lazy loading)
    • Use ApplicationContext as a factory class
      • If the scope of the bean is singleton, and lazy-init is false (the default is false, so you don’t need to set it), then the Bean will be instantiated when the ApplicationContext starts, and the instantiated Bean will be placed in a map structure cache , The next time you use the Bean, it will be taken directly from the cache
      • If the scope of the bean is singleton and lazy-init is true, then the bean is instantiated when the bean is used for the first time
      • If the scope of the bean is prototype, the instantiation of the bean is instantiated when the bean is used for the first time

At last

  • If you feel that you are rewarded after reading it, I hope to give me a thumbs up. This will be the biggest motivation for me to update. Thank you for your support.
  • Welcome everyone to pay attention to my public account [Java Fox], focusing on the basic knowledge of java and computer, I promise to let you get something after reading it, if you don’t believe me, hit me
  • If you have different opinions or suggestions after reading, please comment and share with us. Thank you for your support and love.

image

Welcome to follow the public account "Java Fox" for the latest news

Guess you like

Origin blog.csdn.net/issunmingzhi/article/details/112169454