spring快速入门(二)

一、在spring快速入门(一)的基础上,我们来了解spring是如何解决对象的创建以及对象之间的依赖关系的问题 (比如client中依赖UserAction的具体实现,UserActionImpl中依赖UserDao的具体实现问题)

  1、创建一个java项目、项目结构如下图:

   

  项目具体的搭建步骤如下:

  1.   首先我们想要使用spring框架,当然创建好项目后,需要导入jar包,该项目使用的版本为 spring-framework-2.0-with-dependencies

      由于我们暂时还用不到spring所有的功能,所以需要哪一些功能就导入想要的jar就行了。解压spring资源包后,添加下面的响应jar包到项目中。假设根目录为SPRING_HOME

      spring的依赖包配置
            * SPRING_HOME/dist/spring.jar   (核心jar包)
            * SPRING_HOME/lib/log4j/log4j-1.2.14.jar   (spring依赖的日志包)
            * SPRING_HOME/lib/jakarta-commons/commons-logging.jar  (该包的作用是当存在log4j-1.2.14.jar 时,使用log4j-1.2.14日志记录,当该包不存在时,使用jdk的日志记录,如果jdk的日志不存在,则使用spring的日志记录)

  2.   提供spring的配置文件applicationContext.xml

  3.     提供log4j.properties配置文件 

   4.   在UserActionImpl中提供构造函数,让spring将UserDao实现注入(DI)过来

  5.  让spring管理我们对象的创建和依赖,必须将依赖关系配置到spring的核心配置文件中

  6.    编写我们的客户端

  Client代码: 

package com.murong.client;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.murong.action.UserAction;
import com.murong.action.UserActionImpl;

public class Client {
    
    public static void main(String[] args) {
        
        BeanFactory bf = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserAction userAction = (UserAction) bf.getBean("userActionImpl");
        userAction.addUser("久伴",24);
    }
}

  UserAction:  

package com.murong.action;

public interface UserAction {
        //添加用户
        public void addUser(String name,int age);
}

  UserActionImpl:

package com.murong.action;

import com.murong.dao.UserDao;
import com.murong.dao.UserDaoMysqlImpl;
import com.murong.dao.UserDaoOracleImpl;

public class UserActionImpl implements UserAction{

    private UserDao userDao;
    
    public UserActionImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void addUser(String name, int age) {
        
        userDao.addUser(name, age);
    }

}

  UserDao:

package com.murong.dao;

public interface UserDao {
    
    //添加用户
    public void addUser(String name,int age);
}

  UserDaoMysqlImpl:

package com.murong.dao;

public class UserDaoMysqlImpl implements UserDao {

    @Override
    public void addUser(String name, int age) {
        System.out.println("mysql添加用户成功"+"用户名称:"+name+"年龄:"+age);
    }
}

   UserDaoOracleImpl

package com.murong.dao;

public class UserDaoOracleImpl implements UserDao {

    @Override
    public void addUser(String name, int age) {
        System.out.println("oracle添加用户成功"+"用户名称:"+name+"年龄:"+age);
    }
}

  applicationContext.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"
         xmlns:aop="http://www.springframework.org/schema/aop"
         xmlns:tx="http://www.springframework.org/schema/tx"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
     
     <bean id="userDaoMysqlImpl" class="com.murong.dao.UserDaoMysqlImpl"/> 
  
      <bean id="userDaoOracleImpl" class="com.murong.dao.UserDaoOracleImpl"/> 
      
      <bean id="userActionImpl" class="com.murong.action.UserActionImpl">
          <!-- mysql的实现 -->
          <constructor-arg ref="userDaoMysqlImpl"/>
          <!-- oracle的实现 -->
          <!-- <constructor-arg ref="userDaoOracleImpl"/> -->
      </bean> 
</beans>

   log4j.properties

# For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.xml!
# For all other servers: Comment out the Log4J listener in web.xml to activate Log4J.
log4j.rootLogger=INFO, stdout, logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${petstore.root}/WEB-INF/petstore.log
log4j.appender.logfile.MaxFileSize=512KB
# Keep three backup files.
log4j.appender.logfile.MaxBackupIndex=3
# Pattern to output: date priority [category] - message
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

  

  总结:

  IoC(控制反转):本来是由应用程序管理的对象之间的依赖关系,现在交给了容器管理,这就叫控制反转,即交给了IoC容器,Spring的IoC容器主要使用DI方式实现的。不需要主动查找,对象的查找、定位和创建全部由容器管理

  1、大量减少了Factory和Singleton的数量,使代码层次更加清晰,主要原因是我们不再查找、定位、创建和管理对象之间的依赖关系了,都交给IoC容器管理了

  2、Spring的IoC容器是一个轻量级的容器,没有侵入性,不需要依赖容器的API,也不需要实现一些特殊接口

  3、一个合理的设计最好尽量避免侵入性

原文地址:https://www.cnblogs.com/yuanchaoyong/p/5749423.html