java:Spring框架1(基本配置,简单基础代码实现)

Posted 咫尺天涯是路人丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java:Spring框架1(基本配置,简单基础代码实现)相关的知识,希望对你有一定的参考价值。

1.基本配置:

  

  

  

  步骤一:新建项目并添加spring依赖的jar文件和commons-logging.xx.jar:

 

 

 

 

 

 

  步骤二:编写实体类,DAO及其实现类,Service及其实现类;

 

  步骤三:在src下新建配置文件applicationContext.xml,并配置bean节点和property:

<?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">
        
    <bean id="userinfoJdbcDao" class="cn.zzsxt.dao.impl.UserinfoJdbcDaoImpl"></bean>    
    <bean id="userinfoHibDao" class="cn.zzsxt.dao.impl.UserinfoHibDaoImpl"></bean>    
    <bean id="userinfoService" class="cn.zzsxt.service.impl.UserinfoServiceImpl">
        <property name="userinfoDao" ref="userinfoHibDao"></property>
    </bean>
</beans>        

  

  bean节点:

    id属性:用户自定义的bean的名称,使用ApplicationContext中getBean()根据此id的值从spring容器中获取已创建好的对象。

    class属性:全限定的类名,spring容器会根据此类名动态创建对象

 

  property节点:

    name属性:必须与bean中待注入的属性名称一致,回调其对应的setter方法为该属性赋值。

    ref属性:必须与待注入的对象的id一致,从spring容器中根据ref获取待注入的对象,然后回调setter方法将该对象赋值给属性。

  

  

  步骤四:测试:

public class Test {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserinfoService userinfoService = applicationContext.getBean(UserinfoService.class,"userinfoService");
        Userinfo user = new Userinfo();
        user.setUserId(1);
        user.setUserName("test");
        user.setUserPass("test");
        userinfoService.save(user);
    }
}

 

2.简单基础代码模拟实现:

 

  

 

  application.xml:

  

<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <!-- UserinfoJdbcDaoImpl userinfoJdbcDao = new  UserinfoJdbcDaoImpl()-->
    <bean id="userinfoJdbcDao" class="cn.zzsxt.dao.impl.UserinfoJdbcDaoImpl"></bean>
    <!--UserinfoHibDaoImpl  userinfoHibDao = new  UserinfoHibDaoImpl()-->
    <bean id="userinfoHibDao" class="cn.zzsxt.dao.impl.UserinfoHibDaoImpl"></bean>
    <!--UserinfoServiceImpl userinfoService = new UserinfoServiceImpl()  -->
    <bean id="userinfoService" class="cn.zzsxt.service.impl.UserinfoServiceImpl">
        <!--userinfoService.setUserinfoDao(userinfoJdbcDao);  -->
        <property name="userinfoDao"  ref="userinfoJdbcDao"></property>
    </bean>
</beans>

  

  UserinfoHibDaoImpl:

package cn.zzsxt.dao.impl;

import cn.zzsxt.dao.UserinfoDao;
import cn.zzsxt.entity.Userinfo;

public class UserinfoHibDaoImpl implements UserinfoDao {

    @Override
    public void save(Userinfo user) {
        System.out.println("利用hibernate执行了新增,新增用户"+user);
    }

}

 

  UserinfoJdbcDaoImpl:

 

package cn.zzsxt.dao.impl;

import cn.zzsxt.dao.UserinfoDao;
import cn.zzsxt.entity.Userinfo;

public class UserinfoJdbcDaoImpl implements UserinfoDao {

    @Override
    public void save(Userinfo user) {
        System.out.println("利用jdbc执行了新增,新增用户"+user);
    }

}

  BeanDefination:

package cn.zzsxt.framework;

import java.util.HashMap;
import java.util.Map;

/**
 * 封装配置文件applicationContext.xml中bean节点的信息
 *     <bean id="userinfoService" class="cn.zzsxt.service.impl.UserinfoServiceImpl">
 *        <property name="userinfoDao"  ref="userinfoHibDao"></property>
 *    </bean>
 * @author Think
 *
 */
public class BeanDefination {
    private String beanId;//封装id属性的值
    private String beanClass;//封装class属性的值
    //封装该bean节点的所有property子节点的信息,利用property的name做键,利用property的信息做值
    private Map<String,PropertyDefination> propsMap = new HashMap<String,PropertyDefination>();
    
    public String getBeanId() {
        return beanId;
    }
    public void setBeanId(String beanId) {
        this.beanId = beanId;
    }
    public String getBeanClass() {
        return beanClass;
    }
    public void setBeanClass(String beanClass) {
        this.beanClass = beanClass;
    }
    public Map<String, PropertyDefination> getPropsMap() {
        return propsMap;
    }
    public void setPropsMap(Map<String, PropertyDefination> propsMap) {
        this.propsMap = propsMap;
    }
    @Override
    public String toString() {
        return "BeanDefination [beanId=" + beanId + ", beanClass=" + beanClass + ", propsMap=" + propsMap + "]";
    }
    
}

 

  PropertyDefination:

package cn.zzsxt.framework;
/**
 * 封装applicationContext.xml中property节点的信息
 * <property name="userinfoDao"  ref="userinfoHibDao"></property>
 * @author Think
 *
 */
public class PropertyDefination {
    private String propertyName;//封装name属性的值
    private String propertyRef;//封装ref属性的值
    public String getPropertyName() {
        return propertyName;
    }
    public void setPropertyName(String propertyName) {
        this.propertyName = propertyName;
    }
    public String getPropertyRef() {
        return propertyRef;
    }
    public void setPropertyRef(String propertyRef) {
        this.propertyRef = propertyRef;
    }
    @Override
    public String toString() {
        return "PropertyDefination [propertyName=" + propertyName + ", propertyRef=" + propertyRef + "]";
    }
    
}

 

  UserinfoServiceImpl:

package cn.zzsxt.service.impl;

import cn.zzsxt.dao.UserinfoDao;
import cn.zzsxt.entity.Userinfo;
import cn.zzsxt.service.UserinfoService;

public class UserinfoServiceImpl implements UserinfoService {
    private UserinfoDao userinfoDao;
    
    public void setUserinfoDao(UserinfoDao userinfoDao) {
        this.userinfoDao = userinfoDao;
    }

    @Override
    public void save(Userinfo user) {
        userinfoDao.save(user);
    }
    
}

 

  SxtApplicationContext:

package cn.zzsxt.framework;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import cn.zzsxt.entity.Userinfo;
import cn.zzsxt.service.UserinfoService;

public class SxtApplicationContext {
    //封装所有bean节点的信息,利用bean的id做键,利用bean节点的信息做值
    private Map<String,BeanDefination> beanDefinationsMap = new HashMap<String,BeanDefination>();
    //封装所有动态创建的对象信息,利用bean的id做键,利用创建的对象做值
    private Map<String,Object>  beansMap = new HashMap<String,Object>();
    
    public SxtApplicationContext(){
        parseXML();//解析配置文件
        createObject();//动态创建对象
        injectObject();//为属性注入值:回调该属性的setter方法
    }
    /**
     * 解析applicationContext.xml配置文件信息。
     * 将bean节点封装成BeanDefination对象
     * 将property节点封装成PropertyDefination对象
     * 
     */
    public void parseXML(){ 
        InputStream ips = this.getClass().getResourceAsStream("/applicationContext.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(ips);
            //获取根节点
            Element beans = document.getRootElement();//获取根节点-->beans节点
            Iterator<Element> beanIter = beans.elementIterator();
            while(beanIter.hasNext()){
                Element bean = beanIter.next();//获取bean节点
                String beanId = bean.attributeValue("id");//获取bean节点的id属性值
                String beanClass = bean.attributeValue("class");//获取bean节点的class属性值
                //将bean节点的信息封装成BeanDefination对象
                BeanDefination beanDefination = new BeanDefination();
                beanDefination.setBeanId(beanId);
                beanDefination.setBeanClass(beanClass);
                Iterator<Element> propertyIter = bean.elementIterator();
                while(propertyIter.hasNext()){
                    Element property = propertyIter.next();//获取property节点
                    String propertyName =  property.attributeValue("name");//获取property节点的name属性值
                    String propertyRef =  property.attributeValue("ref");//获取property节点的ref属性值
                    //将property节点的信息封装成PropertyDefination对象
                    PropertyDefination propertyDefination = new PropertyDefination();
                    propertyDefination.setPropertyName(propertyName);
                    propertyDefination.setPropertyRef(propertyRef);
                    //将property节点的信息添加到beanDefination的map中
                    beanDefination.getPropsMap().put(propertyName, propertyDefination);
                }
                //将beanDefination添加到beanDefinationsMap中
                beanDefinationsMap.put(beanId, beanDefination);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 根据配置文件中bean节点的class属性信息动态创建对象,并将创建的对象添加到beansMap中
     */
    public void createObject(){
        try {
            //1.遍历beanDefinationsMap(封装了所有bean节点的信息)
            for (Entry<String,BeanDefination> beanEntry :beanDefinationsMap.entrySet()) {
                String beanId = beanEntry.getKey();//bean的id属性的值
                BeanDefination beanDefination = beanEntry.getValue();//获取bean节点的信息
                String beanClass = beanDefination.getBeanClass();//bean的class属性的值
                Object object = Class.forName(beanClass).newInstance();//根据bean节点的class属性值(全限定的类名)动态创建对象
                //将创建的对象添加到beansMap中,利用beanId做键,利用对象做值
                beansMap.put(beanId, object);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
    
    /**
     * 根据property节点所配置的属性信息,从容器中查找待注入的对象,回调setter方法为属性赋值。
     */
    public void injectObject(){
        try {
            for (Entry<String,BeanDefination> beanEntry :beanDefinationsMap.entrySet()) {
                String beanId = beanEntry.getKey();//bean的id属性的值
                //根据beanId从beansMap中创建的对象
                Object target=getBean(beanId);
                
                BeanDefination beanDefination = beanEntry.getValue();//获取bean节点的信息
                String beanClass = beanDefination.getBeanClass();//bean的class属性的值
                Class clazz = Class.forName(beanClass);//动态加载bean
                Map<String,PropertyDefination> propsMap = beanDefination.getPropsMap();//获取property节点的信息
                for (Entry<String,PropertyDefination> propertyEntry : propsMap.entrySet()) {
                    PropertyDefination propertyDefination = propertyEntry.getValue();//获取property节点的信息
                    String propertyName = propertyDefination.getPropertyName();//获取property的name属性值                    
                    String propertyRef = propertyDefination.getPropertyRef();//获取property的ref属性值
                    
                    Object params = getBean(propertyRef);//根据property中的ref属性值从beansMap获取待注入的对象(要求ref属性的值必须与待注入的bean的id值一致)
                    
                    String setterMethodName = makeSetter(propertyName);//根据property节点的name属性值,获取其对应的setter方法名
                    
                    Method[] ms = clazz.getDeclaredMethods();
                    for (Method method : ms) {
                        String methodName = method.getName();
                        if(methodName.equals(setterMethodName)){
                            //回调setter方法
                            method.invoke(target, params);
                            
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    
    /**
     * 根据beanId从beansMap容器中获取创建的对象
     * @param beanId
     * @return
     */
    public Object getBean(String beanId){
        return beansMap.get(beanId);
    }
    /**
     * 根据属性名称生成对应的setter方法名: set+属性的首字母大写+其余字母
     * @param fieldName
     * @return
     */
    public String makeSetter(String fieldName){
        return "set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
    }
    
    public static void main(String[] args) {
        SxtApplicationContext applicationContext = new SxtApplicationContext();
        UserinfoService userinfoService = (UserinfoService)applicationContext.getBean("userinfoService");
        Userinfo user = new Userinfo();
        user.setUserId(1);
        user.setUserName("admin");
        user.setUserPass("admin");
        userinfoService.save(user);
    }
}

 

3.spring注入(DI):

 

 

 

  application.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: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">
        
    <bean id="userinfoJdbcDao" class="cn.zzsxt.dao.impl.UserinfoJdbcDaoImpl"></bean>    
    <bean id="userinfoHibDao" class="cn.zzsxt.dao.impl.UserinfoHibDaoImpl"></bean>    
    <bean id="userinfoService" class="cn.zzsxt.service.impl.UserinfoServiceImpl">
        <property name="userinfoDao" ref="userinfoHibDao"></property>
    </bean>
</beans>        

 

  beans.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: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">
    <!--
        DI:依赖注入
        1.setter注入:回调属性的setter方法为该属性赋值
            a.为属性注入常量值:使用property的value属性
            b.为属性注入对象:使用property的ref属性
        2.构造方法注入(构造子注入):回调构造方法为属性赋值
     -->    
    <bean id="user" class="cn.zzsxt.entity.Userinfo">
        <property name="userId" value="1"></property>
        <property name="userName" value="zhangsan"></property>
        <property name="userPass" value="123"></property>
    </bean>
    <!-- 
        构造方法注入:constructor-arg index代表的参数的下标 
        a.为属性注入常量值:使用constructor-arg中的value属性
        b.为属性注入对象: 使用constructor-arg中的ref属性
     -->
    <bean id="user2" class="cn.zzsxt.entity.Userinfo2">
        <constructor-arg index="0" value="2"></constructor-arg>
        <constructor-arg index="1" value="lisi"></constructor-arg>
        <constructor-arg index="2" value="1234"></constructor-arg>
    </bean>
    
    <bean id="userinfoJdbcDao" class="cn.zzsxt.dao.impl.UserinfoJdbcDaoImpl"></bean>
    <bean id="userinfoService" class="cn.zzsxt.service.impl.UserinfoServiceImpl">
        <!-- 使用setter注入 -->
<!--         <property name="userinfoDao" ref="userinfoJdbcDao"></property> -->
        <!-- 使用构造函数为属性注入对象 -->
        <constructor-arg index="0" ref="userinfoJdbcDao"></constructor-arg>
    </bean>
</beans>        

 


  beans2.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: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">
   <!-- 为集合属性注入值:在框架的集成中较为常见 -->
   <bean id="myCollection" class="cn.zzsxt.entity.MyCollection">
           <!-- 为list类型的属性注入值 -->
           <property name="list">
               <list>
                   <value>list1</value>
                   <value>list2</value>
                   <value>list3</value>
               </list>
           </property>
           <!-- 为set类型的属性注入值 -->
           <property name="set">
               <set>
                   <value>set1</value>
                   <value>set2</value>
                   <value>set1</value>
               </set>
           </property>
           <!-- 为map类型的属性注入值 -->
           <property name="map">
               <map>
                   <entry key="key1" value="value1"></entry>
                   <entry key="key2" value="value2"></entry>
               </map>
           </property>
           <!-- 为properties类型的属性注入值 -->
           <property name="props">
               <props>
                   <prop key="p-key1">p-value1</prop>
                   <prop key="p-key2">p-value2</prop>
               </props>
           </property>
   </bean>
</beans>        

 


  beans3.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: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">
        
      <bean id="stoneAxe" class="cn.zzsxt.ioc.StoneAxe"></bean>
      <bean id="steelAxe" class="cn.zzsxt.ioc.SteelAxe"></bean>
      <bean id="chinese" class="cn.zzsxt.ioc.Chinese">
          <property name="axe" ref="stoneAxe"></property>
      </bean>
      <bean id="american" class="cn.zzsxt.ioc.American">
          <property name="axe" ref="steelAxe"></property>
      </bean>
</beans>        

  MyCollection:

package cn.zzsxt.entity;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class MyCollection {
    private List list;
    private Set set;
    private Map map;
    private Properties props;
    
    以上是关于java:Spring框架1(基本配置,简单基础代码实现)的主要内容,如果未能解决你的问题,请参考以下文章

8.秋招复习简单整理之Spring面试一般问题

java框架--Spring XML AOP 配置基础

Spring框架由来及IOC的基本概念

想找基于J2EE的网站设计找我们代做

想找基于J2EE的网站设计找我们代做

Spring基础知识详解