Basic understanding about the Spring Framework

Spring in simple terms

First, what is Spring Framework

    Blogger beginners, wrong place please correct me Daniel. Come to the question, in order to know what the Spring framework is to first understand what is the framework. Framework is an integrated set of tools toolkit, or when the house was built general structure. In the development process, some of the fixed code program, in order to reduce the code amount, so the introduction of the "frame." The Spring Framework is an integrated section programming, MVC, Web, entity mapping objects, JDBC and DAO and other functional modules. The core is the Spring Inversion of Control (IoC) and the facing section (AOP). Briefly, Spring is a layered JavaSE / EEfull-stack (stop) lightweight open source framework.

Two, Spring composition

    Spring structure of FIG.

    1, Spring Core: Spring's core container

        One of the most important part of each module in the Spring Bean to manage by the way the organization. Declaratively injection, simple and easy to read.

 

    2, Spring Context: For objects, bean management

  Gets the bean has been initialized by ApplicationContext. In order to achieve inversion of control (IOC) operation. When it comes to control inversion, which is one design principles of object oriented programming, it can be used to reduce the degree of coupling between the computer code. The most common method is called dependency injection (Dependency Injection, referred to as DI), there is a way called "dependent lookup" (Dependency Lookup). By inversion of control, when the object was created by an outside entity for all objects within a regulatory system on which it depends object passed to it. It can be said, it is injected into the subject dependency.

- Paste from Baidu Encyclopedia

  It means you do not need to manage objects, this series of operations to Spring like.

  Use context to create an object:

ClassPathXmlApplicationContext context = new ApplicationContext("beans.xml");

 

 

    3、Spring Dao :管理JDBC

  原生的JDBC:需要手动去数据库的驱动从而拿到对应的连接。

 1         Connection conn = null;
 2         PreparedStatement stat = null;
 3         ResultSet rs = null;
 4         String sql = "select * from user where username = ? and passwd = ?";
 5         try {
 6             conn = dataSource.getConnection();
 7             stat = conn.prepareStatement(sql);
 8             stat.setString(1, username);
 9             stat.setString(2, passwd);
10             rs = stat.executeQuery();
11             if(rs.next()) {
12                 return true;
13             }
14         } catch (SQLException e) {
15             e.printStackTrace();
16         } 

 

 

  However, in the Spring framework, you only need to add this code:

 

bean.xml

1      <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> 
2          <property name="url" value="jdbc:mysql://localhost:3306/stumgr" />
3          <property name="username" value="root" />
4          <property name="password" value="" />
5      </bean>
1    <!-- 1. 扫描注解-->
2     <context:component-scan base-package="bb"/>
3 
4     <!-- 2. 创建JdbcTemplate对象 -->
5     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
6         <property name="dataSource" ref="dataSource"></property>
7     </bean>

 

  The native JDBC to read:

UserDao.java

 1     private DataSource dataSource;
 2     public void setDataSource(DataSource dataSource) {
 3         this.dataSource = dataSource;
 4     }
 5 
 6     public void save() {
 7         try {
 8             String sql = "insert into t_dept(deptName) values('test');";
 9             Connection con = null;
10             Statement stmt = null;
11             // 连接对象
12             con =dataSource.getConnection ();
 13 is              // Run objects 
14              stmt =   con.createStatement ();
 15              // perform 
16              stmt.execute (SQL);
 . 17              
18 is              // Close 
. 19              stmt.close ();
 20 is              con.close ( );
 21 is          } the catch (Exception E) {
 22 is              e.printStackTrace ();
 23 is          }
 24      }

 

 

When necessary, use this:

1  //使用Spring的自动装配
2     @Autowired
3     private JdbcTemplate template;
4 
5     @Override
6     public void save() {
7         String sql = "select * from user";
8         template.query(sql);
9     }

  The method is a method wherein setDateSource Spring packaged, just like it needs to be set value. The method used is JdbcTemplate

 

Third, the following is an imitation of the Spring framework to do login authentication code to help understand:

MyContext.java (Core mimic generation target container)

  . 1  Package com.hxz.spring01.context;
   2  
  . 3  Import as java.lang.reflect.Field;
   . 4  Import the java.util.HashMap;
   . 5  Import the java.util.Iterator;
   . 6  Import a java.util.Map;
   . 7  
  . 8  Import ORG. dom4j.Document;
   . 9  Import org.dom4j.Element;
 10  Import org.dom4j.io.SAXReader;
 . 11  
12 is  public  class MyContext {
 13 is      
14      // Create a Map storing the bean and bean object ID 
15      Map <String, Object> = context new newThe HashMap <String, Object> ();
 16  
. 17      / ** 
18 is       * constructor creates bean object
 . 19       * @param cfgpath
 20 is       * / 
21 is      public MyContext (String cfgpath) {
 22 is  //         parse XML obtain bean 
23 is          SAXReader Reader = new new SAXReader ();
 24          the Document DOC = null ;
 25          
26 is          the try {
 27              DOC = reader.Read (MyContext. class .getClassLoader () the getResource (cfgpath).);
 28              
29              //1, the root node acquires Beans 
30              the Element = the root doc.getRootElement ();
 31 is              the Iterator <the Element> IT = root.elementIterator ();
 32              
33 is              the while (it.hasNext ()) {
 34 is                  // 2, the iterative acquisition sub-node bean id and class 
35                  the Element the bean = it.next ();
 36                  String id = bean.attributeValue ( "id" );
 37 [                  String className = bean.attributeValue ( "class" );
 38 is                  
39                  // . 3, obtained by the class Get an instance of the object bean 
40                  Class = clazz the Class.forName (className);
 41 is                 O = Object clazz.newInstance ();
 42 is                  
43 is                  // . 4, the attribute acquiring propty bean node and cloned into Spring bean container (if not the end) 
44 is                  the Iterator <the Element> propIt = bean.elementIterator ();
 45                  the while (propIt.hasNext ()) {
 46 is                      the Element prop = propIt.next ();
 47                      
48                      // Get propty the name 
49                      String propName = prop.attributeValue ( "name" );
 50                      Field, F = clazz.getDeclaredField (propName );
 51 is                      
52 is                      // Get the value or propty REF 
53 is                      IF(. f.getType () isPrimitive () || f.getType () the equals (String.. class )) {
 54 is                          String value = prop.attributeValue ( "value" );
 55                          f.set (O, value);
 56 is  //                         respond propty attribute value when rigorous analysis performed, the corresponding storage format codes are as follows:
 57 is  //                         Switch (. f.getType () getName ()) {
 58  //                             Case "java.lang.String":
 59  //                                 f.set (O, value);
 60  //                                 BREAK;
 61 is  //                             Case "byte":
 62 //                                f.set(o, Byte.parseByte(value));
 63 //                                break;
 64 //                            case "short":
 65 //                                f.set(o, Short.parseShort(value));
 66 //                                break;
 67 //                            case "int":
 68 //                                f.set(o, Integer.parseInt(value));
 69 //                                break;
 70 //                            case "long":
 71 //                                f.set(o, Long.parseLong(value));
 72 //                                break;
 73 //                            case "char":
 74 //                                f.set(o, value.charAt(0));
 75 //                                break;
 76 //                            case "float":
 77 //                                f.set(o, Float.parseFloat(value));
 78 //                                break;
 79 //                            case "double":
 80 //                                f.set(o, Double.parseDouble(value));
 81 //                                break;
 82 //                            case "boolean":
 83 //                                f.set(o, Boolean.parseBoolean(value));
 84 //                                break;
 85 //                        }
 86                     } else {
 87                         String ref = prop.attributeValue("ref");
 88                         f.set(o, context.get(ref));
 89                     }
90                  }
 91 is                  
92                  // the name of the bean and pressed into the object Map 
93                  context.put (ID, O);
 94              }
 95          } the catch (Exception E) {
 96              e.printStackTrace ();
 97          }
 98          
99      }
 100      
101      / ** 
102       * this method returns the call to the object in the bean
 103       * @param the beanId
 104       * @return 
105       * / 
106      public Object the getBean (String the beanId) {
 107          return context.get(beanId);
108     }
109 
110 }

 

LoginServelet.java

 1 package com.hxz.spring01.servlet;
 2 
 3 import com.hxz.spring01.context.MyContext;
 4 import com.hxz.spring01.dao.UserDao;
 5 
 6 public class LoginServlet {
 7     public String serid;
 8     public int age;
 9     public UserDao dao;
10 
11     public void doPost() {
12         if(dao.findByUsernameAndPasswd("admin", "123456")){
13             
14         } else {
15             System.out.println ( "user name or password error" );
 16          }
 . 17      }
 18 is      
. 19      public  static  void main (String [] args) {
 20 is          MyContext context = new new MyContext ( "the beans.xml" );
 21 is          
22 is          // 2, dao acquired from the context 
23 is          the LoginServlet Login = (the LoginServlet) context.getBean ( "LoginServlet" );
 24          
25          System.out.println (login.serid);
 26 is          System.out.println (login.age);
 27          
28          login.doPost ();
 29      }
 30 
31     public UserDao getDao() {
32         return dao;
33     }
34 
35     public void setDao(UserDao dao) {
36         this.dao = dao;
37     }
38     
39 }

 

 

dao里面就相对简单

dao.java

1 package com.hxz.spring01.dao;
2 
3 public class UserDao {
4 
5     public boolean findByUsernameAndPasswd(String string, String string2) {
6         return false;
7     }
8 
9 }

 

 

接下来就要对配置文件xml进行编写

bean.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
        classpath:/org/springframework/beans/factory/xml/spring-beans-4.3.xsd">

    <!-- 声明一个userdao -->
    <bean id="userDao" class="com.hxz.spring01.dao.UserDao">
    </bean>
    
    <!-- 将userdao依赖与loginServlet -->
    <bean id="loginServlet" class="com.hxz.spring01.servlet.LoginServlet">   
        <property name="serid" value="aaabbbccc"/>
        <property name="age" value="25"/>
        <property name="dao" ref="userDao"/>
    </bean>

</beans>

Guess you like

Origin www.cnblogs.com/Tkning/p/11089096.html