Spring框架基本代码

1.准备阶段:

2.基本引入:

接口:

package com.xk.spring.kp01_hello;
public interface IHello {
    public void nice();
}
//实现类:
package com.xk.spring.kp01_hello;
public class Hello implements IHello {
    public void nice() {
        System.out.println("Hello.nice()");
    }

}
//测试类:
package com.xk.spring.kp01_hello;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
@SuppressWarnings("deprecation")
public class TestHello {
    // 不采用@Autowired注解,不采用自动装配.
    // 采用面向对象编程思路.
    ClassPathResource resource = new ClassPathResource("HelloSpring.xml");
    BeanFactory factory = new XmlBeanFactory(resource);
    IHello hello = new Hello();
    @Test
    public void testName() throws Exception {
        IHello bean = factory.getBean("HelloSpringBean", IHello.class);
        bean.nice();
        System.out.println("~~~~~~~~~~~~~~~~~~~");
        hello.nice();
    }

}

2. 基本模型:

//接口:
package com.xk.spring.kp02_modules;
public interface ITestmoudles {
    public void sayhello();
}
//实现类:
package com.xk.spring.kp02_modules;

public class TestMoudles implements ITestmoudles {

    public void sayhello() {
        System.out.println("TestMoudles.sayhello()");
    }

    public void init() {
        System.out.println("TestMoudles.init()");
    }

    public void destroy() {
        System.out.println("TestMoudles.destroy()");
    }

}
<!-- 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
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="ModulesBean" class="com.xk.spring.modules.TestMoudles" init-method="init" 
    destroy-method="destroy"/>

</beans>
//测试类
package com.xk.spring.kp02_modules;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//面向接口编程
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
// @ContextConfiguration("xml的名字.xml")如果有,则xml的名字不需要是测试类-context
public class TestMoudlesTest {
    /*
     ClassPathResource resource = new ClassPathResource("Moudles.xml");
     BeanFactory factory = new XmlBeanFactory(resource);
     */
    @Autowired //不用new实现类 完全面向接口编程
    BeanFactory factory;

    @Test // 测试
    public void testName() throws Exception {
        ITestmoudles bean = factory.getBean("ModulesBean", ITestmoudles.class);
        bean.sayhello();

    }
}

3.基本传统实现创建bean:

package com.xk.spring.kp03_container.s1_basic;
public interface IContainer {
    public void testcontainer();
}
//实现类:
package com.xk.spring.kp03_container.s1_basic;

public class ContainerImlp implements IContainer {

    public ContainerImlp() {
        System.out.println("ContainerImlp.ContainerImlp()");
    }

    public void init() {
        System.out.println("ContainerImlp.init()");
    }

    public void destroy() {
        System.out.println("ContainerImlp.destory()");
    }

    public void testcontainer() {
        System.out.println("-------------------------");
    }

}
<!-- 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
http://www.springframework.org/schema/beans/spring-beans.xsd">
        <!-- id= "唯一标识" class= "实现类的权限定"-->
    <bean id="testContainerBean" class="com.xk.spring.kp03_container.s1_basic.ContainerImlp" 
    init-method="init" destroy-method="destroy"/> 
    
    <!-- lazy-init:true 告诉Spring容器, 不再在容器启动的时候实例化对应bean -->

</beans>

注:运行时将第一行注释删掉

//测试类:
package com.xk.spring.kp03_container.s1_basic;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class ContainerTest {
    //ApplicationContext: 也是一个接口, 继承了BeanFactory, ApplicationContext容器功能更加全面
    @Autowired
    ApplicationContext appCtx;
    @Test
    public void testName() throws Exception {
        IContainer con = appCtx.getBean("testContainerBean", IContainer.class);
        con.testcontainer();
    }
}

4.静态工厂方法生产bean:

package com.xk.spring.kp03_container.s2_staticcreatebean;

public interface IStaticCreateBean {
    public void creatbean();
}
package com.xk.spring.kp03_container.s2_staticcreatebean;

public class StaticCreateBeanImpl implements IStaticCreateBean {

    @Override
    public void creatbean() {
        System.out.println("------------------------");
    }

    public void init() {
        System.out.println("StaticCreateBeanImpl.init()");
    }

    public void destroy() {
        System.out.println("StaticCreateBeanImpl.destroy()");
    }

}
package com.xk.spring.kp03_container.s2_staticcreatebean;

public class StaticCreateBeanFactory {

    public static StaticCreateBeanImpl creatbean() {
        StaticCreateBeanImpl bean = new StaticCreateBeanImpl();
        bean.init();
        bean.destroy();
        bean.creatbean();
        return bean;
    }

}
package com.xk.spring.kp03_container.s2_staticcreatebean;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class StaticCreateBeanTest {

    @Autowired
    ApplicationContext appCtx;

    @Test
    public void testName() throws Exception {
        IStaticCreateBean bean = appCtx.getBean("StaticCreateBean", IStaticCreateBean.class);
        bean.creatbean();
    }

}
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="StaticCreateBean"
        class="com.xk.spring.kp03_container.s2_staticcreatebean.StaticCreateBeanFactory"
        init-method="init" destroy-method="destroy" factory-method="creatbean" />
</beans>

5.BeanFactory:

package com.xk.spring.kp03_container.s3_factorybeancreate;

public interface IFactoryCreateBean {
    public void factory();
}
package com.xk.spring.kp03_container.s3_factorybeancreate;

public class ImplFactoryCreateBean implements IFactoryCreateBean {
    public ImplFactoryCreateBean() {
        System.out.println("ImplFactoryBeanCreate.ImplFactoryBeanCreate()");
    }

    public void init() {
        System.out.println("ImplFactoryBeanCreate.init()");
    }
    public void destory(){
        System.out.println("ImplFactoryBeanCreate.destory()");
    }
    @Override
    public void factory() {
        System.out.println("ImplFactoryBeanCreate.factory()");
    }

}
package com.xk.spring.kp03_container.s3_factorybeancreate;

import org.springframework.beans.factory.FactoryBean;

//创建bean工厂,只需要一个类实现FactoryBean接口,则Spring框架就会默认为该类是一个工厂类
public class CreateBeanFactory implements FactoryBean<ImplFactoryCreateBean> {

    @Override
    public ImplFactoryCreateBean getObject() throws Exception {
        ImplFactoryCreateBean bean = new ImplFactoryCreateBean();
        return bean;
    }

    @Override
    public Class<?> getObjectType() {
        return ImplFactoryCreateBean.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

}
package com.xk.spring.kp03_container.s3_factorybeancreate;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class FactoryBeanTest {
    /*
     * 自动配置
     * 
     * @Autowired可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作,
     * 这里必须明确:@Autowired是根据类型进行自动装配的,如果需要按名称进行装配,则需要配合@Qualifier[1]使用.
     * @Autowired标注可以放在成员变量上,也可以放在成员变量的set方法上。前者,
     * Spring会直接将UserDao类型的唯一一个bean赋值给userDao这个成员变量;后者,
     * Spring会调用setUserDao方法来将UserDao类型的唯一一个bean装配到userDao这个属性。 Spring
     * 2.5引入了 @Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。
     * 通过 @Autowired的使用来消除set ,get方法。
     */
    @Autowired
    ApplicationContext appCtx;

    @Test
    public void FactoryBean() throws Exception {
        ImplFactoryCreateBean bean = appCtx.getBean("CreateFactoryBean", ImplFactoryCreateBean.class);
        bean.factory();
    }

}
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="CreateFactoryBean"
        class="com.xk.spring.kp03_container.s3_factorybeancreate.ImplFactoryCreateBean"
        init-method="init" destroy-method="factory"  />

</beans>

6:instance实例化创建Bean:

package com.xk.spring.kp03_container.s4_instancecreatebeanFactory;

public interface IInstanceCreateBean {
    public void instanceCreate();
}
package com.xk.spring.kp03_container.s4_instancecreatebeanFactory;

public class ImplInatanceCreateBean implements IInstanceCreateBean {
    public ImplInatanceCreateBean() {
        System.out.println("我是构造......");
    }

    public void init() {
        System.out.println("我是init......");
    }

    public void destroy() {
        System.out.println("我是destroy......");
    }

    @Override
    public void instanceCreate() {
        System.out.println("我是实现方法.......");
    }

}
package com.xk.spring.kp03_container.s4_instancecreatebeanFactory;

public class InstanceCreateFactoryBean {
    public ImplInatanceCreateBean create() {
        ImplInatanceCreateBean bean = new ImplInatanceCreateBean();
        bean.init();
        bean.destroy();
        return bean;
    }

}
package com.xk.spring.kp03_container.s4_instancecreatebeanFactory;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class InstanceCreateFactoryTest {

    @Autowired
    ApplicationContext AppCtx;

    @Test
    public void InstanceFactory() throws Exception {
        IInstanceCreateBean bean = AppCtx.getBean("InstanceCreateFactoryBean", IInstanceCreateBean.class);
        bean.instanceCreate();
    }

}
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="InstanceCreateFactoryBean"
        class="com.xk.spring.kp03_container.s4_instancecreatebeanFactory.ImplInatanceCreateBean"
    init-method="init" destroy-method="destroy"/>

</beans>

7.Scope属性使用:

package com.xk.spring.kp03_container.s5_scope;

public interface IScopeBean {
    public void init();
    public void destroy();
    public void scope();
}
package com.xk.spring.kp03_container.s5_scope;

public class ImplScopeBean implements IScopeBean {
    public ImplScopeBean() {
        System.out.println("我是构造...");
    }

    @Override
    public void init() {
        System.out.println("init...");
    }

    @Override
    public void destroy() {
        System.out.println("destroy...");
    }

    @Override
    public void scope() {
        System.out.println("scope...");
    }

}
package com.xk.spring.kp03_container.s5_scope;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class ScopeBeanTest {
    @Autowired
    ApplicationContext AppCtx;

    @Test
    public void Scope() throws Exception {
        IScopeBean bean1 = AppCtx.getBean("ScopeBean", IScopeBean.class);
        IScopeBean bean2 = AppCtx.getBean("ScopeBean", IScopeBean.class);
        
        System.out.println(bean1==bean2);
        bean1.init();
        bean2.init();
        bean1.destroy();
        bean1.scope();
    }
}
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="ScopeBean" class="com.xk.spring.kp03_container.s5_scope.ImplScopeBean"
        init-method="init" destroy-method="destroy" scope="singleton" />
    <!-- scope: singleton: 单例 每次创建的bean相同;
         prototype: 原型类型, 非单例的, 每次getBean都会创建一个新的对象 
    -->
</beans>

8.Spring和Struts2练习使用:

工程结构:

package com.xk.spring.exercise.dao;

import com.xk.spring.exercise.domain.Student;

public interface IStudentDao {
    public void save(Student stu);
}
package com.xk.spring.exercise.dao.impl;

import org.springframework.stereotype.Repository;

import com.xk.spring.exercise.dao.IStudentDao;
import com.xk.spring.exercise.domain.Student;
@Repository
public class StudentImpl implements IStudentDao {
    @Override
    public void save(Student stu) {
        System.out.println("保存中..."+stu);
    }

}
//domain
package com.xk.spring.exercise.domain;

public class Student {
    private String name;
    private int id;

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", id=" + id + "]";
    }

}
//action层
package com.xk.spring.exercise.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.xk.spring.exercise.domain.Student;
import com.xk.spring.exercise.service.IServiceStudent;
@Controller
public class StudentAction {
    @Autowired
    private IServiceStudent service;

    public void save() {
        Student stud = new Student();
        stud.setName("张三");
        stud.setId(10);
        
        service.save(stud);
    }
}
//Servixe层
//接口
package com.xk.spring.exercise.service;

import com.xk.spring.exercise.domain.Student;

public interface IServiceStudent {
    public void save (Student stu);
}
//实现类:
package com.xk.spring.exercise.service.serviceimpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xk.spring.exercise.dao.IStudentDao;
import com.xk.spring.exercise.domain.Student;
import com.xk.spring.exercise.service.IServiceStudent;
@Service
public class ServiceStudentImpl implements IServiceStudent {
    //需要一个dao的实例;
    @Autowired
    private IStudentDao dao;
    
    @Override
    public void save(Student stu) {
        dao.save(stu);
    }

}
//测试类:
package com.xk.spring.exercise.actionTest;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.xk.spring.exercise.action.StudentAction;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class ActionTest {
    
    @Autowired
    StudentAction student;
    @Test
    public void testActionTest() throws Exception {
    
        student.save();
        
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">

    <context:component-scan base-package="com.xk.spring.exercise"/>
    
</beans>

原文地址:https://www.cnblogs.com/huike/p/6628881.html