Category:线上线下实战
Article From:https://www.cnblogs.com/newAndHui/p/9060381.html

24.springConfiguring DBCP and completing the CRUD operation

  1.Prepare the jar package

  

   2.Edit Product model

 1 package com.day02.ssm.spring.model;
 2 
 3 public class Product{
 4     private Integer id;
 5     private String productName;  //Product name
 6     private Integer salePrice;
 7     private Integer costPrice;
 8 
 9     public Integer getId() {
10         return id;
11     }
12 
13     public void setId(Integer id) {
14         this.id = id;
15     }
16 
17     public String getProductName() {
18         return productName;
19     }
20 
21     public void setProductName(String productName) {
22         this.productName = productName;
23     }
24 
25     public Integer getSalePrice() {
26         return salePrice;
27     }
28 
29     public void setSalePrice(Integer salePrice) {
30         this.salePrice = salePrice;
31     }
32 
33     public Integer getCostPrice() {
34         return costPrice;
35     }
36 
37     public void setCostPrice(Integer costPrice) {
38         this.costPrice = costPrice;
39     }
40 }

Product

 

  3.Edit interface

 1 package com.day02.ssm.spring.dao;
 2 
 3 import com.day02.ssm.spring.model.Product;
 4 
 5 import java.sql.SQLException;
 6 
 7 /**
 8  * Course notes:http://www.cnblogs.com/newAndHui/category/1153640.html
 9  * Interrogative consulting wx:85129834810  */
11 public interface IProductDao {
12     //increase
13     public void save(Product product) throws SQLException;
14     //Delete
15     public void delete(int id);
16     //change
17     public void update(Product product);
18     //check
19     public Product query(int id);
20 
21 }

IProductDao

 

  4.Edit implementation class

 1 package com.day02.ssm.spring.dao.impl;
 2 
 3 import com.day02.ssm.spring.dao.IProductDao;
 4 import com.day02.ssm.spring.model.Product;
 5 import org.apache.commons.dbcp.BasicDataSource;
 6 
 7 import java.sql.Connection;
 8 import java.sql.PreparedStatement;
 9 import java.sql.SQLException;
10 
11 /**
12  * Course notes:http://www.cnblogs.com/newAndHui/category/1153640.html
13  * Interrogative consulting wx:85129834814  */
15 public class ProductDao implements IProductDao {
16     private BasicDataSource basicDataSource;
17     @Override
18     public void save(Product product) {
19         try {
20             //Connect
21             Connection connection = basicDataSource.getConnection();
22             String sql = "INSERT INTO product (product_name,sale_price) VALUES (?,?)";
23             //Create a compilation statement
24             PreparedStatement preparedStatement = connection.prepareStatement(sql);
25             preparedStatement.setString(1,product.getProductName());
26             preparedStatement.setInt(2,product.getSalePrice());
27             //implement
28             preparedStatement.executeUpdate();
29             //release
30             preparedStatement.close();
31             connection.close();
32         } catch (SQLException e) {
33             e.printStackTrace();
34         }
35     }
36 
37     @Override
38     public void delete(int id) {
39 
40     }
41 
42     @Override
43     public void update(Product product) {
44 
45     }
46 
47     @Override
48     public Product query(int id) {
49         return null;
50     }
51 
52     public BasicDataSource getBasicDataSource() {
53         return basicDataSource;
54     }
55 
56     public void setBasicDataSource(BasicDataSource basicDataSource) {
57         this.basicDataSource = basicDataSource;
58     }
59 }

ProductDao

  5.Write the spring configuration file bdcp-config.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4         xsi:schemaLocation="http://www.springframework.org/schema/beans
 5         http://www.springframework.org/schema/beans/spring-beans.xsd">
 6      <!--Configuring dataSources-->
 7     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
 8         <property name="url" value="jdbc:mysql://localhost:3306/station_data"/>
 9         <property name="username" value="root"/>
10         <property name="password" value="admin"/>
11     </bean>
12    <!-- ProductDaoConfiguring Dao-->
13     <bean id="productDao" class="com.day02.ssm.spring.dao.impl.ProductDao">
14         <property name="basicDataSource" ref="dataSource"/>
15     </bean>
16 </beans>

dbcp-config.xml

  6.Introduce the bdcp-config.xml configuration file into the main configuration file (which is easy to forget).

  

  7.Test Dao

 1 package com.day02.ssm.spring.test;
 2 
 3 import com.day02.ssm.spring.dao.impl.ProductDao;
 4 import com.day02.ssm.spring.model.Product;
 5 import com.day02.ssm.spring.model.Ticket;
 6 import org.junit.Test;
 7 import org.junit.runner.RunWith;
 8 import org.springframework.beans.factory.BeanFactory;
 9 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.test.context.ContextConfiguration;
11 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
12 
13 /**
14  * Course notes:http://www.cnblogs.com/newAndHui/category/1153640.html
15  * Interrogative consulting wx:85129834816  */
17 @RunWith(SpringJUnit4ClassRunner.class)//Load the JUnit into the spring container
18 @ContextConfiguration("classpath:spring-config.xml")
19 public class TestProductDao {
20 
21    // private ProductDao productDao=new ProductDao();
22     @Autowired
23     private ProductDao productDao;//Getting Dao objects from spring
24     @Test
25     public void test(){
26         Product product = new Product();
27         product.setProductName("Apple ");
28         product.setSalePrice(89);
29         productDao.save(product);
30     }
31 
32 }

TestProductDao

25.springHard coding in the solution

  1.configuration file

  

  2.Use

  

 

 26.springInheritance in the use of

  

 

 27.AutowiredExplain in detail

  AutowiredAnd Qualifier label
1.Through the @Autowired tag, Spring automatically finds the object of the attribute from the Spring container and injects it to the attribute. (use this trick in production)
2.Third party program: before Spring3.0, you need to manually configure the @Autowired parsing annotate, and Spring will automatically add the parser for the @Autowired tag. Starting from Spring3.0, you can no longer need to change the configuration, butIt can only take effect in the Spring container.
    <context:annotation-config />,
   No matter which version you use, you have to configure it.
3.@AutowiredLabels are attached to a field or a setter method.
4.@AutowiredYou can inject multiple objects into one attribute at the same time.
      public void setXxx(OtherBean1 other1,OtherBean2 other2) {}
5.Using @Autowired tags can inject important objects built into Spring, such as BeanFactory, ApplicationContext.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class SpringTest {
    @Autowired
    private ApplicationContext ctx;
}
6.By default, the @Autowired tag must be able to find the corresponding object, otherwise it will be wrong. However, required=false can be used to avoid this problem: @Autowired (required=false).
7.@AutowiredThe way to find bean:
    1)、First, depending on the type of the dependent object, if it is found, it will be injected directly by using the setter method or the field.
    2)、If multiple matching types are found in the context of Spring, then find them by name, and if they do not match, they will be wrong.
    3)、You can use the @Qualifier (“otherBean”) tag to specify that the dependent object is to follow the id+ type of bean.
public class SomeBean {
    @Autowired
    private OtherBean1 other1;
    @Autowired(required = false)
            @Qualifier(“otherbean2”)
    private OtherBean2 other2;
    public String toString() {
        return “SomeBean [other=” + other1 + “, other2=” + other2 + “]”;
    }
}
 Demo code:

  SomeBean

 1 package com.day02.ssm.spring.model2;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.beans.factory.annotation.Qualifier;
 5 
 6 /**
 7  * Course notes:http://www.cnblogs.com/newAndHui/category/1153640.html
 8  * Interrogative consulting wx:851298348 9  */
10 public class SomeBean {
11     private String name;
12     //Add OtherBean1 objects
13     @Autowired
14     @Qualifier("otherBean11")
15     private OtherBean1 otherBean1;
16     private OtherBean2 otherBean2;
17     
18     public String getName() {
19         return name;
20     }
21 
22     public void setName(String name) {
23         this.name = name;
24     }
25    // @Autowired
26    /* public void setOtherBean1(OtherBean1 otherBean1) {
27         this.otherBean1 = otherBean1;
28     }*/
29   /*  @Autowired
30     public void setTwo(OtherBean1 otherBean1,OtherBean2 otherBean2) {
31         System.out.println("==otherBean1=============otherBean2=====");
32         this.otherBean1 = otherBean1;
33         this.otherBean2 = otherBean2;
34 
35     }*/
36 }

SomeBean

  OtherBean1

 1 package com.day02.ssm.spring.model2;
 2 
 3 /**
 4  * Course notes:http://www.cnblogs.com/newAndHui/category/1153640.html
 5  * Interrogative consulting wx:851298348 6  */
 7 public class OtherBean1 {
 8     private String name;
 9 
10     public String getName() {
11         return name;
12     }
13 
14     public void setName(String name) {
15         this.name = name;
16     }
17 }

OtherBean1

  OtherBean2

 1 package com.day02.ssm.spring.model2;
 2 
 3 /**
 4  * Course notes:http://www.cnblogs.com/newAndHui/category/1153640.html
 5  * Interrogative consulting wx:851298348 6  */
 7 public class OtherBean2 {
 8     private String name;
 9 
10     public String getName() {
11         return name;
12     }
13 
14     public void setName(String name) {
15         this.name = name;
16     }
17 }

OtherBean2

     springconfiguration file

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans
 6         http://www.springframework.org/schema/beans/spring-beans.xsd
 7          http://www.springframework.org/schema/context
 8           http://www.springframework.org/schema/context/spring-context.xsd">
 9     <!--Open the annotation -->10     <context:annotation-config/>
11     <!--Give someBean to spring to manage -->12     <bean id="someBean" class="com.day02.ssm.spring.model2.SomeBean">
13         <property name="name" value="someBean-1"/>
14     </bean>
15 
16     <!--Give OtherBean1 to spring to manage -->17     <bean id="otherBean17" class="com.day02.ssm.spring.model2.OtherBean1">
18         <property name="name" value="otherBean1-1"/>
19     </bean>
20 
21     <bean id="otherBean11" class="com.day02.ssm.spring.model2.OtherBean1">
22         <property name="name" value="otherBean1-11"/>
23     </bean>
24 
25     <!--Give OtherBean2 to spring to manage -->26     <bean id="otherBean2" class="com.day02.ssm.spring.model2.OtherBean2">
27         <property name="name" value="otherBean2-2"/>
28     </bean>
29 </beans>

View Code

  Test code

 1 package com.day02.ssm.spring.model2;
 2 
 3 import org.junit.Test;
 4 import org.junit.runner.RunWith;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.context.ApplicationContext;
 7 import org.springframework.test.context.ContextConfiguration;
 8 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 9 
10 /**
11  * Course notes:http://www.cnblogs.com/newAndHui/category/1153640.html
12  * Interrogative consulting wx:85129834813  */
14 @RunWith(SpringJUnit4ClassRunner.class)//Load the JUnit into the spring container
15 @ContextConfiguration("classpath:spring-config2.xml")
16 public class TestSomeBean {
17 
18     @Autowired(required = false)
19      private SomeBean  someBean;
20    // @Autowired
21    // private ApplicationContext ctx;
22 
23     @Test
24     public void test() {
25        // SomeBean someBean = (SomeBean) ctx.getBean("someBean11");
26         System.out.println("someBean"+ someBean);
27     }
28 
29 }

TestSomeBean

 28.ResourceLabel

  @ResourceLabel:
  1,@ResourceThe label is the label of the JavaEE specification;
  2,@ResourceTags can also be used in field or setter methods;
  3,You can also use @Resource tags to inject some important objects built into spring, such as BeanFactory.ApplicationContext.
  4,@ResourceA matching object must be required;
  5,<context:annotation-config>The parser of @Autowired tag is introduced, and the parser of @Resource is introduced.
  6,@ResourceThe way the label looks for bean:
    1),First look for the name,If you find it, use setter or field injection;
    2),If you can’t find it according to your name, look for it by type,But if more than one matching type is found, it is wrong.
    3),You can directly use the name attribute to specify the name of the bean; however, if the specified name can only be found according to name, if it is not found, it will not be followed by type.
public class SomeBean {
    @Resource(name=”otherBean1″)
    private OtherBean1 other1;
    @Resource(name=”otherBean2″)
    private OtherBean2 other2;
    public String toString() {
        return “SomeBean [otherBean=” + other1 + “, otherBean2=”
                + other2 + “]”;
    }

 

@Resource(name = “other1”) And @Autowired, @Qualifier (“other1”):
1:Use Autowired tags to make code and Spring coupled together. If you do not use Spring one day, you have to change the source code.Autowired
2:ResourceThe label itself is javaEE, and there is no coupling problem in itself.
Whatever group you use, ask: you have to master it.

29.Use annotations to simplify IoC

  Using labels to simplify IoC:
    1.To use tags to complete IoC, you must have a IoC tag parser.
    Use context:component-scan to scan the bean that spring needs to manage.
    base-packageJust tell spring, which packages and sub packages to scan bean, if multiple packages need to be scanned, just use commas to separate multiple packages.
     <!–   Scanning packet –>
    <context:component-scan base-package=”com.day02.ssm.spring.model2″ />
    <!–Open the annotation –>
    <context:annotation-config/>

  2.Annotating Bean: @Component
  By default, the name of the class is used directly (the lowercase letter is the name of the bean).
  If you want to modify the name of bean, use the value property to redefine the name of bean.
  @Component(“otherbean”)
  public class OtherBean {}
  

  SpringZero configuration

  

 

  IoCAnd DI operation, annotation or XML?
1):Using XML, intuitionistic, low intrusive, unified configuration.
2):Using annotations, simple and fast, is not very intuitive, so that the configuration is dispersed.
Sometimes, XML can only be used, and annotations can not be used.
   For example, configuring a DataSource.
     You can’t go to the DataSource class to label it.
In general, we use XML to make a unified configuration. If there is a special configuration, we can use annotations to assist.
 The two must be mastered.

 

Link of this Article: 05_ssm base (four) Spring base two

Leave a Reply

Your email address will not be published. Required fields are marked *