zoukankan      html  css  js  c++  java
  • Spring学习总结二——SpringIOC容器二

    一:指定bean的依赖关系

    例如examplebean对象依赖examplebean1对象,那么在创建examplebean对象之前就

    需要先创建examplebean1对象。

    1:创建Examplebean1类:

     1 /**
     2  * 
     3  */
     4 package com.hlcui.dao;
     5 
     6 /**
     7  * @author Administrator
     8  * 
     9  */
    10 public class ExampleBean1 {
    11     public ExampleBean1() {
    12         System.out.println("实例化ExampleBean1...");
    13     }
    14 }

    2:在spring容器配置文件中配置ExampleBean1对象,并且指定bean的依赖关系

    depends-on="ExampleBean1"
    1 <!-- 实例化ExampleBean对象 -->
    2     <bean id="exampleBean" class="com.hlcui.dao.ExampleBean" lazy-init="true" 
    3     init-method="init" destroy-method="destroy" scope="singleton" depends-on="ExampleBean1"></bean>
    4 
    5     <!-- 实例化ExampleBean1对象 -->
    6     <bean id="ExampleBean1" class="com.hlcui.dao.ExampleBean1"
    7         lazy-init="true"></bean>

    3:运行测试方法:

    1 @Test
    2     /**测试bean的依赖关系*/
    3     public void testNewExampleBean() {
    4         ApplicationContext ac = getApplicationContext();
    5         ExampleBean eb1 = ac.getBean("exampleBean", ExampleBean.class);
    6         System.out.println(eb1);
    7     }

    通过结果可以看出先实例化依赖对象,再创建对象。

    二:spring实现setter注入到jdbcDatasource数据库连接参数

    1:导入jar包,在spring原有的支持包的基础上导入,oracle数据库的驱动包

    2:创建JDBCDataSource类

     1 /**
     2  * 
     3  */
     4 package com.hlcui.dao;
     5 
     6 import java.sql.Connection;
     7 import java.sql.DriverManager;
     8 import java.sql.SQLException;
     9 
    10 /**
    11  * @author Administrator
    12  * 
    13  */
    14 public class JDBCDataSource {
    15 
    16     private String driverClass;
    17 
    18     private String url;
    19 
    20     private String username;
    21 
    22     private String password;
    23 
    24     public String getDriverClass() {
    25         return driverClass;
    26     }
    27 
    28     public void setDriverClass(String driverClass) {
    29         try {
    30             Class.forName(driverClass); // 注册数据库驱动
    31             this.driverClass = driverClass;
    32         } catch (ClassNotFoundException e) {
    33             e.printStackTrace();
    34         }
    35 
    36     }
    37 
    38     public String getUrl() {
    39         return url;
    40     }
    41 
    42     public void setUrl(String url) {
    43         this.url = url;
    44     }
    45 
    46     public String getUsername() {
    47         return username;
    48     }
    49 
    50     public void setUsername(String username) {
    51         this.username = username;
    52     }
    53 
    54     public String getPassword() {
    55         return password;
    56     }
    57 
    58     public void setPassword(String password) {
    59         this.password = password;
    60     }
    61 
    62     // 获取数据库连接
    63     public Connection getConn() throws SQLException {
    64         return DriverManager.getConnection(url, username, password);
    65     }
    66 
    67     // 关闭数据库连接
    68     public void closeConn(Connection conn) {
    69         if (null != conn) {
    70             try {
    71                 conn.close();
    72             } catch (SQLException e) {
    73                 e.printStackTrace();
    74             }
    75         }
    76     }
    77 }

    3:配置bean对象

    核心代码如下:

    1 <!-- 配置jdbc数据源 -->
    2     <bean id="jdbcDatasource" class="com.hlcui.dao.JDBCDataSource">
    3         <property name="driverClass" value="oracle.jdbc.OracleDriver"></property>
    4         <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>
    5         <property name="username" value="system"></property>
    6         <property name="password" value="orcl"></property>
    7     </bean>

    4:测试方法以及运行结果

     1 @Test
     2     /**测试获取jdbc连接*/
     3     public void testJdbcConnection() {
     4         try {
     5             ApplicationContext ac = getApplicationContext();
     6             JDBCDataSource ds = ac.getBean("jdbcDatasource",
     7                     JDBCDataSource.class);
     8             System.out.println(ds.getConn());
     9         } catch (Exception e) {
    10             e.printStackTrace();
    11         }
    12 
    13     }

    从运行结果可以看出,得到了jdbc连接对象。

    三:spring实现构造器注入参数

    1:创建业务实体类对象User

     1 /**
     2  * 
     3  */
     4 package com.hlcui.dto;
     5 
     6 /**
     7  * @author Administrator
     8  *
     9  */
    10 public class User {
    11     private int id;
    12     private String name;
    13     private String pwd;
    14     private String phone;
    15     public User(int id, String name, String pwd, String phone) {
    16         super();
    17         this.id = id;
    18         this.name = name;
    19         this.pwd = pwd;
    20         this.phone = phone;
    21     }
    22     public User(String name, String pwd, String phone) {
    23         super();
    24         this.name = name;
    25         this.pwd = pwd;
    26         this.phone = phone;
    27     }
    28     public int getId() {
    29         return id;
    30     }
    31     public void setId(int id) {
    32         this.id = id;
    33     }
    34     public String getName() {
    35         return name;
    36     }
    37     public void setName(String name) {
    38         this.name = name;
    39     }
    40     public String getPwd() {
    41         return pwd;
    42     }
    43     public void setPwd(String pwd) {
    44         this.pwd = pwd;
    45     }
    46     public String getPhone() {
    47         return phone;
    48     }
    49     public void setPhone(String phone) {
    50         this.phone = phone;
    51     }
    52     @Override
    53     public int hashCode() {
    54         final int prime = 31;
    55         int result = 1;
    56         result = prime * result + id;
    57         result = prime * result + ((name == null) ? 0 : name.hashCode());
    58         result = prime * result + ((phone == null) ? 0 : phone.hashCode());
    59         result = prime * result + ((pwd == null) ? 0 : pwd.hashCode());
    60         return result;
    61     }
    62     @Override
    63     public boolean equals(Object obj) {
    64         if (this == obj)
    65             return true;
    66         if (obj == null)
    67             return false;
    68         if (getClass() != obj.getClass())
    69             return false;
    70         User other = (User) obj;
    71         if (id != other.id)
    72             return false;
    73         if (name == null) {
    74             if (other.name != null)
    75                 return false;
    76         } else if (!name.equals(other.name))
    77             return false;
    78         if (phone == null) {
    79             if (other.phone != null)
    80                 return false;
    81         } else if (!phone.equals(other.phone))
    82             return false;
    83         if (pwd == null) {
    84             if (other.pwd != null)
    85                 return false;
    86         } else if (!pwd.equals(other.pwd))
    87             return false;
    88         return true;
    89     }
    90     @Override
    91     public String toString() {
    92         return "User [id=" + id + ", name=" + name + ", phone=" + phone
    93                 + ", pwd=" + pwd + "]";
    94     }
    95     
    96 }
    View Code

    2:创建oracle的sql脚本,并且执行sql

     1 --创建表users
     2 Create Table Users(
     3 Id Number(6,2),
     4 Name Varchar2(30),
     5 Pwd  Varchar2(50),
     6 Phone Varchar2(50),
     7 Primary Key(Id),
     8 constraint name unique(name)
     9 );
    10 
    11 --创建序列
    12 Create Sequence Seq_Users;
    13 
    14 --向表中插入数据
    15 Insert Into Users (Id,Name,Pwd,Phone) Values(Seq_Users.Nextval,'Tom','123','312123232');
    16 Insert Into Users (Id,Name,Pwd,Phone) Values(Seq_Users.Nextval,'Jack','456','312123232');
    17 Insert Into Users (Id,Name,Pwd,Phone) Values(Seq_Users.Nextval,'Lucy','789','312123232');
    18 commit;

    3:创建UserDAO接口以及其实现类

     1 package com.hlcui.dao;
     2 
     3 import com.hlcui.dto.User;
     4 
     5 /**
     6  * @author Administrator
     7  *
     8  */
     9 public interface UserDAO {    
    10     public User findByName(String name);
    11 }
     1 /**
     2  * 
     3  */
     4 package com.hlcui.dao.impl;
     5 
     6 import java.sql.Connection;
     7 import java.sql.PreparedStatement;
     8 import java.sql.ResultSet;
     9 
    10 import com.hlcui.dao.JDBCDataSource;
    11 import com.hlcui.dao.UserDAO;
    12 import com.hlcui.dto.User;
    13 
    14 /**
    15  * @author Administrator
    16  * 
    17  */
    18 public class OracleUserDAO implements UserDAO {
    19 
    20     private JDBCDataSource jdbcDataSource;
    21 
    22     public OracleUserDAO(JDBCDataSource jdbcDataSource) {
    23         this.jdbcDataSource = jdbcDataSource;
    24     }
    25 
    26     public User findByName(String name) {
    27         Connection conn = null;
    28         PreparedStatement prep = null;
    29         ResultSet rs = null;
    30         User user = null;
    31         try {
    32             conn = jdbcDataSource.getConn();
    33             String sql = "select id,pwd,phone from users where name=?";
    34             prep = conn.prepareStatement(sql);
    35             prep.setString(1, name);
    36             rs = prep.executeQuery();
    37             while (rs.next()) {
    38                 int id = rs.getInt("id");
    39                 String pwd = rs.getString("pwd");
    40                 String phone = rs.getString("phone");
    41                 user = new User(id, name, pwd, phone);
    42             }
    43         } catch (Exception e) {
    44             e.printStackTrace();
    45         }
    46         return user;
    47     }
    48 
    49 }

    注:这里使用preparedstatement进行预编译,可以有效的防止sql注入,select * from tableName  where username='' and password = '' or 1=1,

    这里的1=1是无论什么条件都会满足的,所以会登录进网站。经常使用ibatis框架的朋友对 where 1=1 and ... 比较熟悉,这里是为了防止后面的sql动态拼接

    不满足条件造成 select * from tableName where 这种情况,这里区分一下。

    4:在spring容器配置文件配置OracleUserDao的bean对象

     1 <!-- 配置jdbc数据源 -->
     2     <bean id="jdbcDatasource" class="com.hlcui.dao.JDBCDataSource">
     3         <property name="driverClass" value="oracle.jdbc.OracleDriver"></property>
     4         <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>
     5         <property name="username" value="system"></property>
     6         <property name="password" value="orcl"></property>
     7     </bean>
     8     
     9     <!-- 配置userDao对象 -->
    10     <bean id="userDao" class="com.hlcui.dao.impl.OracleUserDAO">
    11         <constructor-arg index="0" ref="jdbcDatasource"/>
    12     </bean>

    constructor-arg元素代表构造器注入,index是参数的下表,0说明是第一个元素,如果有多个参数,可以使用如下格式:

    1 <constructor-arg index="0">   
    2         <value>first parameter</value>   
    3     </constructor-arg>   
    4     <constructor-arg index="1">   
    5         <value>second parameter</value>   
    6     </constructor-arg>   

    5:测试读取数据库中的user对象

    1 @Test
    2     /**测试从oracle数据库中读取数据*/
    3     public void testGetUser() {
    4         ApplicationContext ac = getApplicationContext();
    5         UserDAO dao = ac.getBean("userDao", OracleUserDAO.class);
    6         User user = dao.findByName("Tom");
    7         System.out.println(user);
    8     }

    成功读取User对象!

  • 相关阅读:
    爬虫示例
    S20_DAY23--课堂笔记
    python--常用模块之正则
    S20_DAY22--课堂笔记
    win10系统重装
    CCF 命令行选项
    CCF 任务调度
    CCF 出现次数最多的数
    CCF ISBN
    CCF 最大的矩形
  • 原文地址:https://www.cnblogs.com/warrior4236/p/6049238.html
Copyright © 2011-2022 走看看