spring框架01

2018-04-27  本文已影响31人  RLM233

1 spring框架概述

1.1 什么是spring

1.2 spring的优点

1.3 spring体系结构

spring体系结构

2 IoC案例

2.1 IoC概述

2.2 所需jar包

2.3 创建目标类

public interface UserService {
    
    public void addUser();
}
public class UserServiceImpl implements UserService {

    @Override
    public void addUser() {
        System.out.println("a_ico add user");
    }

}

2.4 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">
    <!-- 配置service 
            <bean> 配置需要创建的对象
            id:用于之后从spring容器获得实例时使用的
            class:需要创建实例的全限定类名 -->
    <bean id="userServiceId" class="com.itheima.a_ioc.UserServiceImpl"></bean>
</beans>

2.5 测试

@Test
public void demo02(){
    //从spring容器获得
    //1 获得容器
    String xmlPath = "com/itheima/a_ioc/beans.xml";
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
    //2 获得内容,不需要自己new,都是从spring容器获得
    UserService userService = (UserService) applicationContext.getBean("userServiceId");
    userService.addUser();
}

3 DI案例

3.1 DI概述

3.2 创建dao接口和dao实现类

public interface BookDao {

    public void addBook();
}
public class BookDaoImpl implements BookDao {

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

3.3 创建bookService接口和bookService实现类

public interface BookService {

    public void addBook();
}
public class BookServiceImpl implements BookService {
    
    // 方式1:之前,接口=实现类
    //private BookDao bookDao = new BookDaoImpl();
    // 方式2:接口 + setter
    private BookDao bookDao;
    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }

    @Override
    public void addBook() {
        this.bookDao.addBook();
    }
}

3.4 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">
    
        <!-- 
        模拟spring执行过程
        创建service实例:BookService bookService = new BookServiceImpl() IoC  <bean>
        创建dao实例:BookDao bookDao = new BookDaoImpl()         IoC
        将dao设置给service:bookService.setBookDao(bookDao);     DI   <property>
        
        <property> 用于进行属性注入
            name: bean的属性名,通过setter方法获得
                setBookDao ##> BookDao  ##> bookDao
            ref :另一个bean的id值的引用
     -->
    
    <!-- 创建service -->
    <bean id="bookServiceImplId" class="b_di.BookServiceImpl">
        <property name="bookDao" ref="bookDaoImplId"></property>
    </bean>
    
    <!-- 创建dao实例 -->
    <bean id="bookDaoImplId" class="b_di.BookDaoImpl"></bean>
</beans>

3.5 测试

public class Test {

    @org.junit.Test
    public void test01(){
        String xmlPath="b_di/applicationContext.xml";
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
        BookService bookService=applicationContext.getBean("bookServiceImplId",BookService.class);
        bookService.addBook();
    }
}

4 核心API

@Test
public void demo02(){
    //使用BeanFactory  --第一次条用getBean实例化
    String xmlPath = "com/itheima/b_di/beans.xml";
    
    BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(xmlPath));
    
    BookService bookService = (BookService) beanFactory.getBean("bookServiceId");
    
    bookService.addBook();
}

5 bean的实例化方式

5.1 默认构造

5.2 静态工厂

public interface UserService {
    public void addUser();
}
public class UserServiceImpl implements UserService {

    @Override
    public void addUser() {
        System.out.println("静态工厂");
    }
}
public class MyBeanFactory {

    public static UserService createService(){
        return new UserServiceImpl();
    }
}
<?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">

    <!-- 将静态工厂创建的实例交予spring 
        class 确定静态工厂全限定类名
        factory-method 确定静态方法名
    -->
    <bean id="userServiceImplId" class="c_static.MyBeanFactory" factory-method="createService"></bean>
</beans>
@org.junit.Test
public void test01(){
    String xmlPath="c_static/applicationContext.xml";
    ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
    UserService userService=applicationContext.getBean("userServiceImplId",UserService.class);
    userService.addUser();
}

5.3 实例工厂

public interface UserService {
    public void addUser();
}
public class UserServiceImpl implements UserService {

    @Override
    public void addUser() {
        System.out.println("实例工厂");
    }
}
public class MyBeanFactory {

    public UserService createService(){
        return new UserServiceImpl();
    }
}
<?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="myBeanFactorlId" class="d_factory.MyBeanFactory"></bean>
    
    <!-- factory-bean:确定工厂实例
         factory-method:确定普通方法 -->
    <bean id="userServiceImplId" factory-bean="myBeanFactorlId" factory-method="createService"></bean>
</beans>
public class Test {

    @org.junit.Test
    public void test01(){
        String xmlPath="d_factory/applicationContext.xml";
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
        UserService userService=applicationContext.getBean("userServiceImplId",UserService.class);
        userService.addUser();
    }
}

6 Bean的种类

FB fb = new FB();
return fb.getObject();

7 作用域

类别 说明
singleton 在spring ioc容器中仅存在一个Bean实例,Bean以单例方式存在,默认值
prototype 每次从容器中调用Bean时,都返回一个新的实例,即每次都调用getBean()时,相当于执行new XxxBean()
request 每次HTTP请求都会创建一个新的Bean,该作用域仅适用于WebApplicationContext环境
session 同一个HTTP Session共享一个Bean,不同Session使用不同Bean,仅适用于WebApplicationContext环境
globalSession 一般用户Portlet应用环境,该作用域仅适用于WebApplicationContext环境
<bean id="userServiceId" class="com.itheima.d_scope.UserServiceImpl" 
        scope="prototype" ></bean>

8 生命周期

<bean id="" class="" init-method="初始化方法名称"  destroy-method="销毁的方法名称">
public interface UserService {
    public void addUser();
}
public class UserServiceImpl implements UserService {

    @Override
    public void addUser() {
        System.out.println("lifecycle...");
    }
    
    public void myInit(){
        System.out.println("初始化");
    }
    
    public void myDestory(){
        System.out.println("销毁");
    }
}
<?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">
    
    <!-- init-method 用于配置初始化方法,准备数据等
         destroy-method 用于配置销毁方法,清理资源等 -->
    <bean id="userServiceImplId" class="f_lifecycle.UserServiceImpl" init-method="myInit" destroy-method="myDestory"></bean>
</beans>
/**
 * 1. 容器必须close,销毁方法才执行
 * 2. 必须是单例的
 */
public class Test {

    @org.junit.Test
    public void test01() throws Exception{
        String xmlPath="f_lifecycle/applicationContext.xml";
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
        UserService userService=applicationContext.getBean("userServiceImplId",UserService.class);
        userService.addUser();
        
        //使用反射调用close方法
        applicationContext.getClass().getMethod("close").invoke(applicationContext);
    }
    
    @org.junit.Test
    public void test02(){
        String xmlPath="f_lifecycle/applicationContext.xml";
        ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
        UserService userService=applicationContext.getBean("userServiceImplId",UserService.class);
        userService.addUser();
        
        //使用ClassPathXmlApplicationContext调用close
        applicationContext.close();
    }
}

9 后处理Bean:BeanPostProcessor

public interface UserService {
    public void addUser();
}
public class UserServiceImpl implements UserService {

    @Override
    public void addUser() {
        System.out.println("BeanPostProcessor 后处理Bean...");
    }
    
    public void myInit(){
        System.out.println("初始化");
    }
    
    public void myDestroy(){
        System.out.println("销毁");
    }
}
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println("前方法: "+bean);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(final Object bean, String beanName)
            throws BeansException {
        System.out.println("后方法: "+beanName);
        
        // bean 目标对象
        // 生成 jdk 代理
        return Proxy.newProxyInstance(MyBeanPostProcessor.class.getClassLoader(), 
                                      bean.getClass().getInterfaces(), 
                                      new InvocationHandler() {
                                        
                                        @Override
                                        public Object invoke(Object proxy, Method method, Object[] args)
                                                throws Throwable {
                                            System.out.println("开启事务");
                                            //执行目标方法
                                            Object obj=method.invoke(bean, args);
                                            System.out.println("提交事务");
                                            return null;
                                        }
                                    });
    }
}
<?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">
    
    <!-- init-method 用于配置初始化方法,准备数据等
         destroy-method 用于配置销毁方法,清理资源等 -->
    <bean id="userServiceImplId" class="g_lifecycle_beanPostProcessor.UserServiceImpl" init-method="myInit" destroy-method="myDestroy"></bean>
    
    <!-- 将后处理的实现类注册给spring -->
    <bean class="g_lifecycle_beanPostProcessor.MyBeanPostProcessor"></bean>
</beans>
@org.junit.Test
public void test01() {
    String xmlPath="g_lifecycle_beanPostProcessor/applicationContext.xml";
    ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
    UserService userService=applicationContext.getBean("userServiceImplId",UserService.class);
    userService.addUser();
    
    //使用ClassPathXmlApplicationContext调用close
    applicationContext.close();
}

10 属性的依赖注入

10.1 依赖注入方式

10.2 构造注入

public class User {

    private int id;
    private String name;
    private int age;

    public User(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public User(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}
<?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">
    
    <!-- 构造方法注入 
        <constructor-arg> 用于配置构造方法一个参数argument
            name :参数的名称
            value:设置普通数据
            ref:引用数据,一般是另一个bean id值
            
            index :参数的索引号,从0开始 。如果只有索引,匹配到了多个构造方法时,默认使用第一个。
            type :确定参数类型
        例如:使用名称name
            <constructor-arg name="username" value="jack"></constructor-arg>
            <constructor-arg name="age" value="18"></constructor-arg>
        例如2:类型type 和 索引 index
            <constructor-arg index="0" type="java.lang.String" value="1"></constructor-arg>
            <constructor-arg index="1" type="java.lang.Integer" value="2"></constructor-arg>
    -->
    <bean id="userId" class="h_gouZao.User">
        <constructor-arg index="0" type="String" value="张三"></constructor-arg>
        <constructor-arg index="1" type="int" value="25"></constructor-arg>
    </bean>
</beans>
@org.junit.Test
public void test01() {
    String xmlPath="h_gouZao/applicationContext.xml";
    ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
    User u=(User) applicationContext.getBean("userId");
    System.out.println(u);
}

10.3 setter注入

public class Address {

    private String addr;
    private int tel;
    
    public String getAddr() {
        return addr;
    }
    
    public void setAddr(String addr) {
        this.addr = addr;
    }
    
    public int getTel() {
        return tel;
    }
    
    public void setTel(int tel) {
        this.tel = tel;
    }

    @Override
    public String toString() {
        return "Address [add=" + addr + ", tel=" + tel + "]";
    }
}
public class Person {

    private String name;
    private int age;

    private Address homeAddr;
    private Address companyAddr;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Address getHomeAddr() {
        return homeAddr;
    }

    public void setHomeAddr(Address homeAddr) {
        this.homeAddr = homeAddr;
    }

    public Address getCompanyAddr() {
        return companyAddr;
    }

    public void setCompanyAddr(Address companyAddr) {
        this.companyAddr = companyAddr;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", homeAddr="
                + homeAddr + ", companyAddr=" + companyAddr + "]";
    }
}
<?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">
    
    <!-- setter方法注入 
        * 普通数据 
            <property name="" value="值">
            等效
            <property name="">
                <value>值</value>
            </property>
        * 引用数据
            <property name="" ref="另一个bean">
            等效
            <property name="">
                <ref bean="另一个bean"/>
    -->
                
    <bean id="personId" class="i_setter.Person">
        <property name="name" value="张三"></property>
        <property name="age" value="23"></property>
        
        <property name="homeAddr" ref="homeAddrId"></property>
        <property name="companyAddr" ref="companyAddrId"></property>
    </bean>
    
    <bean id="homeAddrId" class="i_setter.Address">
        <property name="addr" value="上海"></property>
        <property name="tel" value="163"></property>
    </bean>

    <bean id="companyAddrId" class="i_setter.Address">
        <property name="addr" value="南京"></property>
        <property name="tel" value="126"></property>
    </bean>
</beans>
@org.junit.Test
public void test01() {
    String xmlPath="i_setter/applicationContext.xml";
    ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
    Person p=(Person) applicationContext.getBean("personId");
    System.out.println(p);
}

10.4 P命名空间

<?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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 
1. P命名空间使用前需添加命名空间: xmlns:p="http://www.springframework.org/schema/p"
2. <bean p:属性名="普通值"  p:属性名-ref="引用值">
 -->

    <bean id="personId" class="j_p.Person" 
    p:name="张三" p:age="23" 
    p:homeAddr-ref="homeAddrId" p:companyAddr-ref="companyAddrId"></bean>

    <bean id="homeAddrId" class="j_p.Address" p:addr="上海" p:tel="12345678"></bean>
    <bean id="companyAddrId" class="j_p.Address" p:addr="南京" p:tel="666"></bean>
</beans>

10.5 集合注入

<?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">

    <!-- 
        集合的注入都是给<property>添加子标签
            数组:<array>
            List:<list>
            Set:<set>
            Map:<map> ,map存放k/v 键值对,使用<entry>描述
            Properties:<props>  <prop key=""></prop>
            
        普通数据:<value>
        引用数据:<ref>
    -->
    <bean id="collDataId" class="k_coll.CollData" >
        <property name="arrayData">
            <array>
                <value>DS</value>
                <value>DZD</value>
                <value>屌丝</value>
                <value>屌中屌</value>
            </array>
        </property>
        
        <property name="listData">
            <list>
                <value>姓名1</value>
                <value>姓名2</value>
                <value>姓名3</value>
            </list>
        </property>
        
        <property name="setData">
            <set>
                <value>张三</value>
                <value>李四</value>
                <value>王五</value>
            </set>
        </property>
        
        <property name="mapData">
            <map>
                <entry key="jack" value="杰克"></entry>
                <entry>
                    <key><value>rose</value></key>
                    <value>肉丝</value>
                </entry>
            </map>
        </property>
        
        <property name="propsData">
            <props>
                <prop key="高富帅">嫐</prop>
                <prop key="白富美">嬲</prop>
                <prop key="男屌丝">挊</prop>
            </props>
        </property>
    </bean>
</beans>

10.6 SpEl

<!-- 
<property name="cname" value="#{'jack'}"></property>
<property name="cname" value="#{customerId.cname.toUpperCase()}"></property>
    通过另一个bean,获得属性,调用的方法
<property name="cname" value="#{customerId.cname?.toUpperCase()}"></property>
    ?.  如果对象不为null,将调用方法
-->
<bean id="customerId" class="com.itheima.f_xml.d_spel.Customer" >
    <property name="cname" value="#{customerId.cname?.toUpperCase()}"></property>
    <property name="pi" value="#{T(java.lang.Math).PI}"></property>
</bean>

11 基于注解

11.1 注解分类

11.2 注解示例

<?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">
        
    <context:component-scan base-package="m_zhuJie02"></context:component-scan>
                           
</beans> 
    @org.junit.Test
    public void test01(){
        String xmlPath="m_zhuJie02/applicationContext.xml";
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
        StudentAction studentAction=(StudentAction) applicationContext.getBean("StudentActionID");
        studentAction.execute();
    }
@Controller("StudentActionID")
public class StudentAction {

    //按照类型注入
    @Autowired
    private StudentService studentService;

    public void execute(){
        studentService.addStudent();
    }
}
@Service
public class StudentServiceImpl implements StudentService {

//  @Qualifier("studentDaoID")
//  @Autowired
    @Resource(name="studentDaoID")
    private StudentDao studentDao;

    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }

    @Override
    public void addStudent() {
        studentDao.save();
    }
}
@Repository("studentDaoID")
public class StudentDaoImpl implements StudentDao {

    @Override
    public void save() {
        System.out.println("dao");
    }
}
上一篇 下一篇

猜你喜欢

热点阅读