2022-09-28 The sixth group Zhang Ningjie Spring framework_01

bean life cycle

  • Lifecycle: the complete process from creation to death
  • bean life cycle: the overall process of beans from creation to destruction
  • Bean lifecycle control: do something after the bean is created and before it is destroyed
  • specific description
    • Initialize the container
      1. object creation (memory allocation)
      2. execute constructor
      3. Perform property injection (set operation)
      4. Execute the bean initialization method
    • use bean s
      1. perform business operations
    • close/destroy container
      1. Execute the bean destroy method

Two ways to destroy bean s

  • close() violent way

  • registerShutdownHook()

  • public static void main( String[] args ) {
            ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
            BookDao bookDao = (BookDao) ctx.getBean("bookDao");
            bookDao.save();
            //Register the shutdown hook function, call this function before the virtual machine exits, and close the container
            //ctx.registerShutdownHook();
            //close the container
            ctx.close();
        }
    
  • Provides life cycle control

  • public class BookDaoImpl implements BookDao {
        public void save() {
            System.out.println("book dao save ...");
        }
        //Indicates the operation corresponding to bean initialization
        public void init(){
            System.out.println("init...");
        }
        //Indicates the corresponding operation before the bean is destroyed
        public void destory(){
            System.out.println("destory...");
        }
    
    }
    
  • Configuring Lifecycle Control Methods

  • <!--init-method: set up bean Initialize the lifecycle callback function-->
    <!--destroy-method: set up bean Destroy lifecycle callback function, only for singleton objects-->
    <bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl" init-method="init" destroy-method="destory"/>
    

Two ways of dependency injection

setter injection

  • simple type

  • reference type

    • Define a reference type property in a bean and provide an accessible set method

    • public class BookDaoImpl implements BookDao {
          private String databaseName;
          private int connectionNum;
          //setter injection requires providing the set method of the object to be injected
          public void setConnectionNum(int connectionNum) {
              this.connectionNum = connectionNum;
          }
          //setter injection requires providing the set method of the object to be injected
          public void setDatabaseName(String databaseName) {
              this.databaseName = databaseName;
          }
      
          public void save() {
              System.out.println("book dao save ..."+databaseName+","+connectionNum);
          }
      }
      
    • Use the property tag value attribute to inject simple type data in the configuration

    • <!--inject simple types-->
          <bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl">
              <!--property Tag: set injection properties-->
              <!--name Attribute: Set the injected attribute name, which is actually set method name-->
              <!--value Attribute: Set inject simple type data value-->
              <property name="connectionNum" value="100"/>
              <property name="databaseName" value="mysql"/>
          </bean>
      

Constructor injection

  • simple type

  • reference type

    • Define reference type properties in bean s and provide accessible constructors

    • public class BookServiceImpl implements BookService{
          private BookDao bookDao;
          private UserDao userDao;
      
          public BookServiceImpl(BookDao bookDao, UserDao userDao) {
              this.bookDao = bookDao;
              this.userDao = userDao;
          }
      
          public void save() {
              System.out.println("book service save ...");
              bookDao.save();
              userDao.save();
          }
      }
      
      
    • Use the constructor-arg tag ref attribute to inject reference type objects in the configuration

    •  <bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"/>
          <bean id="bookService" class="com.itheima.service.impl.BookServiceImpl">
              <constructor-arg name="userDao" ref="userDao"/>
              <constructor-arg name="bookDao" ref="bookDao"/>
          </bean>
      
    • Use the constructor-arg tag type attribute in the configuration to set the injection by parameter type

    • <bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl">
              <!--Injection based on constructor parameter type-->
              <constructor-arg type="int" value="10"/>
              <constructor-arg type="java.lang.String" value="mysql"/>
      </bean>
      
    • Use the constructor-arg tag index attribute in the configuration to set the injection by parameter type

    • <bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl">
              <!--Injection based on constructor parameter position-->
              <constructor-arg index="0" value="mysql"/>
              <constructor-arg index="1" value="100"/>
      </bean>
      

Dependency injection method selection

  • Force dependencies to use constructors, and use setter injections to have a probability of not injecting null objects
  • Optional dependencies are performed using setter injection, which is highly flexible
  • The Spring framework advocates the use of constructors. Most of the third-party frameworks use the form of constructor injection for data initialization, which is relatively strict.
  • If necessary, you can use both at the same time, use constructor injection to complete mandatory dependency injection, and use setter injection to complete optional dependency injection
  • In the actual development process, it is also necessary to analyze the actual situation. If the controlled object does not provide a setter method, it must use constructor injection.
  • Self-developed modules are recommended to use setter injection

Depends on autowiring

  • Use the bean tag autowire attribute to set the type of autowiring in the configuration

  • <bean class="com.itheima.dao.impl.BookDaoImpl"/>
        <!--autowire Properties: Turn on autowiring, usually use by-type wiring-->
    <bean id="bookService" class="com.itheima.service.impl.BookServiceImpl" autowire="byType"/>
    

Relying on autowiring features

  • Autowiring is used for reference type dependency injection and cannot operate on simple types
  • When using assembly by type (byType), you must ensure that bean s of the same type in the container are unique. It is recommended to use
  • When using assembly by name (byName), you must ensure that a bean with the specified name in the container is used. The dependent variable name is coupled with the configuration, which is not recommended.
  • The priority of autowiring is lower than that of setter injection and constructor injection, and the autowiring configuration is invalid when it occurs at the same time

Collection injection

  • <bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl">
            <!--array injection-->
            <property name="array">
                <array>
                    <value>100</value>
                    <value>200</value>
                    <value>300</value>
                </array>
            </property>
            <!--list Collection injection-->
            <property name="list">
                <list>
                    <value>itcast</value>
                    <value>itheima</value>
                    <value>boxuegu</value>
                    <value>chuanzhihui</value>
                </list>
            </property>
            <!--set Collection injection-->
            <property name="set">
                <set>
                    <value>itcast</value>
                    <value>itheima</value>
                    <value>boxuegu</value>
                    <value>boxuegu</value>
                </set>
            </property>
            <!--map Collection injection-->
            <property name="map">
                <map>
                    <entry key="country" value="china"/>
                    <entry key="province" value="henan"/>
                    <entry key="city" value="kaifeng"/>
                </map>
            </property>
            <!--Properties injection-->
            <property name="properties">
                <props>
                    <prop key="country">china</prop>
                    <prop key="province">henan</prop>
                    <prop key="city">kaifeng</prop>
                </props>
            </property>
       </bean>
    

Third-party configuration resource management

  • import druid coordinates

  • <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.16</version>
    </dependency>
    
  • Configure the datasource object as a spring managed bean

  • <!--    manage DruidDataSource object-->
    <bean class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/spring_db"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
    </bean>
    

load properties

  • Enable context namespace

  • <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="
                http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context.xsd">
    </beans>
    
  • Use the context namespace to load the specified properties file

  • <!--classpath:*.properties  :    Set to load all the current project classpath properties document-->
    <!--system-properties-mode properties: whether to load system properties-->
    <context:property-placeholder location="classpath*:*.properties" system-properties-mode="NEVER"/>
    <!--classpath*:*.properties  :   Set to load the current project classpath and all dependencies that the current project depends on jar all in the package properties document-->
    
  • Use ${} to read loaded property value

  • <!--    illustrate: idea Automatic Identification ${}The loaded attribute value needs to be manually clicked to view the original writing format-->
    <property name="username" value="${jdbc.username}"/>
    

container

  • Create a container
  • get bean
  • container class hierarchy
  • BeanFactory

Core container summary

container related

  • BeanFactory is the top-level interface of the IoC container. When the BeanFactory object is initialized, the loaded bean s are loaded lazily.
  • The ApplicationContext interface is the core interface of the Spring container, and the bean s are loaded immediately when initialized
  • The ApplicationContext interface provides basic bean operation related methods and extends functions through other interfaces
  • ApplicationContext interface commonly used initialization class
    • ClassPathXmlApplicationContext
    • FileSystemXmlApplicationContext

bean related

  • id,name,class,scope,init-method,destroy-method,autowire,factory-method,factory-bean,lazy-init

Dependency injection related

  • constructor-arg name ref
  • constructor-arg name value
  • constructor-arg type index
  • property name ref
  • property name value
  • property name list

Annotation development

Annotation development definition bean

  • Defining bean s with @Component

  • @Component("bookDao")
    public class BookDaoImpl implements BookDao {
        
    }
    @Component
    public class BookServiceImpl implements BookService {
        
    }
    
  • Loading bean s through component scanning in the core configuration file

  • <context:component-scan base-package="com.itheima"/>
    
  • Spring provides three derived annotations of the @Component annotation

    • @Controller: used for presentation layer bean definitions
    • @Service: used for business layer bean definitions
    • @Repository: for data layer bean definitions

Pure Annotation Development

  • Spring 3.0 upgrades the pure annotation development mode, uses Java classes to replace configuration files, and opens the Spring rapid development channel

  • Java classes replace Spring core configuration files

  • <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           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
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
        <context:component-scan base-package="com.itheima"/>
    </beans>
    
  • //Declare the current class as the Spring configuration class
    @Configuration
    //Set the bean scan path, multiple paths are written in string array format
    @ComponentScan({"com.itheima.service","com.itheima.dao"})
    public class SpringConfig {
    }
    
  • Read the Spring core configuration file to initialize the container object Switch to read the Java configuration class to initialize the container object

  • //Load the configuration file to initialize the container
    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    //Load the configuration class to initialize the container
    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    

bean scope and life cycle

  • Use @Scope to define bean scope

  • Use @PostConstruct, @PreDestroy to define the bean life cycle

  • @Repository
    //@Scope sets the scope of the bean
    @Scope("singleton")
    public class BookDaoImpl implements BookDao {
    
        public void save() {
            System.out.println("book dao save ...");
        }
        //@PostConstruct sets the initialization method of the bean
        @PostConstruct
        public void init() {
            System.out.println("init ...");
        }
        //@PreDestroy sets the destroy method of the bean
        @PreDestroy
        public void destroy() {
            System.out.println("destroy ...");
        }
    
    }
    

Dependency Injection (annotated version)

automatic assembly

  • Use the @Autowired annotation to enable autowiring mode (by type)

  • Use the @Qualifier annotation to enable the specified name to wire the bean

  • @Service
    public class BookServiceImpl implements BookService {
        //@Autowired: inject reference type, autowire mode, default by type
        @Autowired
        //@Qualifier: Wire by bean name when autowiring beans
        @Qualifier("bookDao")
        private BookDao bookDao;
    	//setBookDao has been removed
        public void save() {
            System.out.println("book service save ...");
            bookDao.save();
        }
    }
    
  • Note: Autowiring creates objects based on reflection design and violently reflects corresponding properties to initialize data for private properties, so there is no need to provide setter methods

  • Note: Autowiring recommends using the no-argument constructor to create objects (default), if no corresponding constructor is provided, please provide the only constructor

  • Note: The @Qualifier annotation cannot be used alone, it must be used in conjunction with the @Autowire annotation

  • Simple Type Injection with @Value

  • @Repository("bookDao")
    public class BookDaoImpl implements BookDao {
        //@Value: inject simple types (no need to provide set method)
        @Value("${name}")
        private String name;
    }
    
  • Load properties file

    • Use the @PropertySource annotation to load the properties file

    • Note: The path only supports single file configuration, please use array format configuration for multiple files, wildcards are not allowed*

    • @Configuration
      @ComponentScan("com.itheima")
      //@PropertySource loads the properties configuration file
      @PropertySource({"jdbc.properties"})
      public class SpringConfig {
      }
      

third party

bean management

  • Configure third-party beans with @bean

  • @Configuration
    public class SpringConfig {
        @Bean
        public DataSource dataSource(){
            DruidDataSource ds = new DruidDataSource();
            ds.setDriverClassName(driver);
            ds.setUrl(url);
            ds.setUsername(userName);
            ds.setPassword(password);
            return ds;
        }
    }
    
  • Add a separate configuration class to the core configuration

  • Method 1: Imported

  • public class JdbcConfig {
        @Bean
        public DataSource dataSource(){
            DruidDataSource ds = new DruidDataSource();
       	    //Related configuration
            return ds;
        }
    }
    
  • Use the @Import annotation to manually add the configuration class to the core configuration. This annotation can only be added once. Please use the array format for multiple data.

  • @Configuration
    @Import(JdbcConfig.class)
    public class SpringConfig {
    
    }
    
  • Add a separate configuration class to the core configuration

  • Method 2: Scanning

  • @Configuration
    public class JdbcConfig {
        @Bean
        public DataSource dataSource(){
            DruidDataSource ds = new DruidDataSource();
       	    //Related configuration
            return ds;
        }
    }
    
  • Use the @ComponentScan annotation to scan the package where the configuration class is located and load the corresponding configuration class information

  • @Configuration
    @ComponentScan({"com.itheima.config","com.itheima.service","com.itheima.dao"})
    public class SpringConfig {
        
    }
    

bean dependency injection

  • Simple Type Dependency Injection

  • public class JdbcConfig {
        //1. Define a method to get the object to be managed
        @Value("com.mysql.jdbc.Driver")
        private String driver;
        @Value("jdbc:mysql://localhost:3306/spring_db")
        private String url;
        @Value("root")
        private String userName;
        @Value("root")
        private String password;
        //2. Add @Bean to indicate that the return value of the current method is a bean
        //@Bean modified method, the parameters are automatically assembled according to the type
        @Bean
        public DataSource dataSource(BookDao bookDao){
            System.out.println(bookDao);
            DruidDataSource ds = new DruidDataSource();
            ds.setDriverClassName(driver);
            ds.setUrl(url);
            ds.setUsername(userName);
            ds.setPassword(password);
            return ds;
        }
    }
    
  • Reference Type Dependency Injection

  • @Bean
    public DataSource dataSource(BookService bookService){
        System.out.println(bookService);
        DruidDataSource ds = new DruidDataSource();
        //property settings
        return ds;
    }
    
  • Reference type injection only needs to set the formal parameters for the bean definition method, and the container will automatically assemble the object according to the type

Annotation Development Summary

XML configuration vs annotation configuration

Spring integrates MyBatis

  • MyBatis program core object analysis

  • //Initialize SqlSessionFactory
    		// 1. Create the SqlSessionFactoryBuilder object
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            // 2. Load the SqlMapConfig.xml configuration file
            InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml.bak");
            // 3. Create SqlSessionFactory object
            SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
    //get connection, get implementation
            // 4. Get SqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession();
            // 5. Execute the SqlSession object to execute the query and get the result User
            AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
    //Get data layer interface
            Account ac = accountDao.findById(2);
            System.out.println(ac);
    //close the connection
            // 6. Free up resources
            sqlSession.close();
    
  • Integrate MyBatis

  • //Initialize property data
    <configuration>
        <properties resource="jdbc.properties"></properties>
    //Initialize type alias
        <typeAliases>
            <package name="com.itheima.domain"/>
        </typeAliases>
    //initialize dataSource
        <environments default="mysql">
            <environment id="mysql">
                <transactionManager type="JDBC"></transactionManager>
                <dataSource type="POOLED">
                    <property name="driver" value="${jdbc.driver}"></property>
                    <property name="url" value="${jdbc.url}"></property>
                    <property name="username" value="${jdbc.username}"></property>
                    <property name="password" value="${jdbc.password}"></property>
                </dataSource>
            </environment>
        </environments>
     //Initialize mapping configuration
        <mappers>
            <package name="com.itheima.dao"></package>
        </mappers>
    </configuration>
    

Tags: Java

Posted by azsolo on Wed, 28 Sep 2022 20:36:16 +0930