spring框架01

1 spring框架概述

1.1 什么是spring

  • spring是一个轻量级(依赖资源少、销毁的资源少)的开源框架,spring的核心是控制反转(IoC)和面向切面(AOP)
  • spring是一个分层的JavaSE/EE full-stack(一站式)轻量级开源框架
    • web层:struts,spring MVC
    • service层:spring
    • dao层:hibernate,mybatis,jdbcTemplate,spring dateaa

1.2 spring的优点

  • 方便解耦,简化开发(高内聚低耦合)
    • spring就是一个大工厂(容器),可以将所有对象创建和依赖关系维护,交给Spring管理
    • spring工厂是用于生成bean
  • AOP编程的支持
    • spring提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能
  • 声明式事务的支持
    • 只需要通过配置就可以完成对事务的管理,而无需手动编程
  • 方便程序的测试
    • spring对Junit4支持,可以通过注解方便的测试spring程序
  • 方便集成各种优秀框架
    • spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如:Struts、Hibernate、MyBatis、Quartz等)的直接支持
  • 低JavaEE API的使用难度
    • spring 对JavaEE开发中非常难用的一些API(JDBC、JavaMail、远程调用等),都提供了封装,使这些API应用难度大大降低

1.3 spring体系结构

spring体系结构
  • spring核心容器:beans、core、context、expression

2 IoC案例

2.1 IoC概述

  • IoC意为:控制反转(Inverse of Control)
  • 之前开发中,直接new一个对象即可。现在将此步骤翻转给spring,由spring创建对象实例
  • 需要实例对象时,从spring工厂(容器)中获得,需要将实现类的全限定名称配置到xml文件中

2.2 所需jar包

  • 4个核心包(beans、core、context、expression)
  • 1个依赖包(commons-loggins...jar)


    jar包

2.3 创建目标类

  • 提供UserService接口和实现类
  • 获得UserService实现类的实例
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配置文件

  • 位置:任意,开发中一般在classpath下(src)
  • 名称:任意,开发中常用applicationContext.xml
  • 内容:添加schema约束
  • 约束文件位置:spring-framework-3.2.0.RELEASE\docs\spring-framework-reference\html\ xsd-config.html
<?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概述

  • DI:Dependency Injection,依赖注入
    • 依赖:一个对象需要使用另一个对象
    • 注入:通过setter方法进行另一个对象实例设置

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

  • API结构图


    核心API
  • BeanFactory:这是一个工厂,用于生成任意bean,采取延迟加载,第一次getBean时才会初始化Bean
  • ApplicationContext:是BeanFactory的子接口,功能更强大。(国际化处理、事件传递、Bean自动装配、各种不同应用层的Context实现)。当配置文件被加载,就进行对象实例化
    • ClassPathXmlApplicationContext用于加载classpath(类路径、src)下的xml,加载xml运行时位置 -->/WEB-INF/classes/...xml
    • FileSystemXmlApplicationContext用于加载指定盘符下的xml,加载xml运行时位置 --> /WEB-INF/...xml,通过java web ServletContext.getRealPath() 获得具体盘符
@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配置
<?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配置
<?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的种类

  • 普通bean:之前操作的都是普通bean,<bean id="" class="A">,spring直接创建A实例,并返回
  • FactoryBean:是一个特殊的bean,具有工厂生成对象能力,只能生成特定的对象。bean必须使用FactoryBean接口,此接口提供方法getObject()用于获得特定bean。<bean id="" class="FB">先创建FB实例,使用调用getObject()方法,并返回方法的返回值
FB fb = new FB();
return fb.getObject();
  • BeanFactory 和 FactoryBean 对比
    • BeanFactory:工厂,用于生成任意bean
    • 特殊bean,用于生成另一个特定的bean。例如:ProxyFactoryBean,此工厂bean用于生产代理。<bean id="" class="....ProxyFactoryBean">获得代理对象实例,AOP使用

7 作用域

  • 作用域:用于确定创建bean实例的个数
类别 说明
singleton 在spring ioc容器中仅存在一个Bean实例,Bean以单例方式存在,默认值
prototype 每次从容器中调用Bean时,都返回一个新的实例,即每次都调用getBean()时,相当于执行new XxxBean()
request 每次HTTP请求都会创建一个新的Bean,该作用域仅适用于WebApplicationContext环境
session 同一个HTTP Session共享一个Bean,不同Session使用不同Bean,仅适用于WebApplicationContext环境
globalSession 一般用户Portlet应用环境,该作用域仅适用于WebApplicationContext环境
  • 取值
    • singleton:单例,默认值
    • prototype:多例,每执行一次getBean将获得一个实例。例如:struts整合spring,配置action多例
  • 配置信息
<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配置
<?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

  • spring 提供一种机制,只要实现此接口BeanPostProcessor,并将实现类提供给spring容器,spring容器将自动执行,在初始化方法前执行before(),在初始化方法后执行after(),spring提供工厂勾子,用于修改实例对象,可以生成代理对象,是AOP底层
  • 创建接口
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配置
<?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 依赖注入方式

  • 手动装配:一般进行配置信息都采用手动
    • 基于xml装配:构造方法、setter方法
    • 基于注解装配
  • 自动装配:struts和spring整合可以自动装配
    • byType:按类型装配
    • byName:按名称装配
    • constructor:构造装配
    • auto:不确定装配

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配置
<?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注入

  • address实体类
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 + "]";
    }
}
  • person实体类
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配置
<?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命名空间

  • 对“setter方法注入”进行简化,替换<property name="属性名">,而是在<bean p:属性名="普通值" p:属性名-ref="引用值">
  • 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>进行统一编程,所有的内容都使用value
    • <property name="" value="#{表达式}">
    • #{123}、#{'jack'}数字、字符串
    • #{beanId}另一个bean引用
    • #{beanId.propName}操作数据
    • #{beanId.toString()}执行方法
    • #{T(类).字段|方法}静态方法或字段
<!-- 
<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 注解分类

  • @Component("id")取代<bean id="" class="">
  • web开发,提供3个@Component注解衍生注解(功能一样)取代<bean class="">
    • @Repositorydao层
    • @Serviceservice层
    • @Controllerweb层
  • 依赖注入,给私有字段设置,也可以给setter方法设置
    • 普通值使用@Value("")
    • 引用值
      • 按照类型注入@Autowired
      • 按照名称注入
        @Autowired
        @Qualifier("名称")
        
      • 按照名称注入@Resource("名称"),此注解由jdk提供,以上两个注解则由spring提供
  • 生命周期注解
    • 初始化@PostConstruct
    • 销毁@PreDestroy
  • 作用域注解
    • 多例@Scope("prototype")
    • 单例@Scope("singleton")

11.2 注解示例

  • xml配置
    • 使用注解类前需添加命名空间,让spring扫描含有注解类
    • xmlns:context="http://www.springframework.org/schema/context"
    • http://www.springframework.org/schema/context
    • http://www.springframework.org/schema/context/spring-context.xsd
<?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> 
  • 测试类
    • 加载配置文件,根据StudentActionID找到控制层
    @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();
    }
  • action控制层
    • 控制层依赖service业务层,将业务层按照类型注入,也可以按照名称注入
@Controller("StudentActionID")
public class StudentAction {

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

    public void execute(){
        studentService.addStudent();
    }
}
  • service实现类
    • service业务层依赖dao数据层,将dao注入给service
@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();
    }
}
  • dao实现类
@Repository("studentDaoID")
public class StudentDaoImpl implements StudentDao {

    @Override
    public void save() {
        System.out.println("dao");
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,306评论 4 370
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,657评论 2 307
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,928评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,688评论 0 220
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,105评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,024评论 1 225
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,159评论 2 318
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,937评论 0 212
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,689评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,851评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,325评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,651评论 3 263
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,364评论 3 244
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,192评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,985评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,154评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,955评论 2 279

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,111评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,430评论 6 342
  • 文章作者:Tyan博客:noahsnail.com 3.4 Dependencies A typical ente...
    SnailTyan阅读 4,046评论 2 7
  • 时隔三年,再次来到白河湾漂流,从北四环哥哥家出发,走了持续2个小时的山路。 弯弯绕绕,兜兜转转,山路崎岖真美! 景...
    67fbaec5208f阅读 281评论 0 0
  • 刚毕业的时候和一个陌生的女孩一起在北京租了一套两居室。当时只想好好工作,和室友和同事好好相处一年下来,体检的时候才...
    简让阅读 128评论 0 0