Spring 1 控制反转、依赖注入

摘要:
--配置服务配置要创建的对象id:用于稍后从spring容器获取实例的类:要创建的实例的完全限定类名--˃1.3测试publicvoid demo02(){//从spring容器中获取//1获取容器StringxmlPath=“com/itheima/aioc/beans.xml” ; ApplicationContextapplicationContext=newClassPathXmlApplicationContext;//2.获取内容——您不需要获取自己的新内容,但可以获取UserServiceuserService=applicationContext。从spring容器中获取Bean;userService.addUser();}2.1依赖注入DI依赖:一个对象需要使用另一个对象注入:通过setter方法设置另一个实例。

1.1 Spring的核心是控制反转(IoC)和面向切面(AOP)

学习spring之前的开发中通过new创建一个对象,有了spring之后,spring创建对象实例-IoC控制反转,之后需要实例对象时从spring工厂(容器)中获得。

1.2 配置文件

位置:src

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

1.3 测试

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();
		
	}

2.1 依赖注入DI

依赖:一个对象需要使用另一个对象

注入:通过setter方法进行另一个对象实例设置。

2.2  创建dao和service

2.21 dao

public interface BookDao {
    
    public void addBook();

}
public class BookDaoImpl implements BookDao {

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

}

2.22 service

public interface BookService {

    public abstract 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();
    }

}

 

2.3 配置文件

<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   class="com.itheima.b_di.BookServiceImpl">
        <property name="bookDao" ref="bookDaoId"></property>
    </bean>
    
    <!-- 创建dao实例 -->
    <bean   class="com.itheima.b_di.BookDaoImpl"></bean>
    

</beans>

2.4 测试

    @Test
    public void demo01(){
        //从spring容器获得
        String xmlPath = "com/itheima/b_di/beans.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        BookService bookService = (BookService) applicationContext.getBean("bookServiceId");
        
        bookService.addBook();
        
    }

3.1 装配Bean基于XML

3种bean的实例化方法:默认构造、静态工厂、实例工厂

3.2 默认构造

<bean id="" class="">  必须提供默认构造

3.3 静态工厂

用于生成实例对象,所有的方法必须是static

<bean id=""  class="工厂全限定类名"  factory-method="静态方法">

3.31 工厂类

public class MyBeanFactory {
    
    /**
     * 创建实例
     * @return
     */
    public static UserService createService(){
        return new UserServiceImpl();
    }
}

3.32 spring配置

    <!-- 将静态工厂创建的实例交予spring 
        class 确定静态工厂全限定类名
        factory-method 确定静态方法名
    -->
    <bean   class="com.itheima.c_inject.b_static_factory.MyBeanFactory" factory-method="createService"></bean>

3.4实例工厂

必须先有工厂实例对象,通过实例对象创建对象。提供所有的方法都是“非静态”的。

3.41 工厂类

/**
 * 实例工厂,所有方法非静态
 *
 */
public class MyBeanFactory {
    
    /**
     * 创建实例
     * @return
     */
    public UserService createService(){
        return new UserServiceImpl();
    }

}

3.42 spring配置

    <!-- 创建工厂实例 -->
    <bean   class="com.itheima.c_inject.c_factory.MyBeanFactory"></bean>
    <!-- 获得userservice 
        * factory-bean 确定工厂实例
        * factory-method 确定普通方法
    -->
    <bean   factory-bean="myBeanFactoryId" factory-method="createService"></bean>
    

3.5 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。

       FactoryBean:特殊bean,用于生成另一个特定的bean。例如:ProxyFactoryBean ,此工厂bean用于生产代              理。<bean id="" class="....ProxyFactoryBean"> 获得代理对象实例。AOP使用

 

3.6 属性依赖注入

3.61 目标类

public class User {
    
    private Integer uid;
    private String username;
    private Integer age;
    
    public User(Integer uid, String username) {
        super();
        this.uid = uid;
        this.username = username;
    }
    
    public User(String username, Integer age) {
        super();
        this.username = username;
        this.age = age;
    }
    

3.62 spring配置

    <!-- 构造方法注入 
        * <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   class="com.itheima.f_xml.a_constructor.User" >
        <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>
<!-- setter方法注入 
        * 普通数据 
            <property name="" value="值">
            等效
            <property name="">
                <value>* 引用数据
            <property name="" ref="另一个bean">
            等效
            <property name="">
                <ref bean="另一个bean"/>
    
    -->
    <bean   class="com.itheima.f_xml.b_setter.Person">
        <property name="pname" value="阳志"></property>
        <property name="age">
            <value>1234</value>
        </property>
        
        <property name="homeAddr" ref="homeAddrId"></property>
        <property name="companyAddr">
            <ref bean="companyAddrId"/>
        </property>
    </bean>
    
    <bean   class="com.itheima.f_xml.b_setter.Address">
        <property name="addr" value="阜南"></property>
        <property name="tel" value="911"></property>
    </bean>
    <bean   class="com.itheima.f_xml.b_setter.Address">
        <property name="addr" value="北京八宝山"></property>
        <property name="tel" value="120"></property>
    </bean>

3.63 集合注入

<!-- 
        集合的注入都是给<property>添加子标签
            数组:<array>
            List:<list>
            Set:<set>
            Map:<map> ,map存放k/v 键值对,使用<entry>描述
            Properties:<props>  <prop key=""></prop>  【】
            
        普通数据:<value>
        引用数据:<ref>
    -->
    <bean   class="com.itheima.f_xml.e_coll.CollData" >
        <property name="arrayData">
            <array>
                <value>DS</value>
                <value>DZD</value>
                <value>屌丝</value>
                <value>屌中屌</value>
            </array>
        </property>
        
        <property name="listData">
            <list>
                <value>于嵩楠</value>
                <value>曾卫</value>
                <value>杨煜</value>
                <value>曾小贤</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>

4.1 装配bean基于注解

使用注解取代xml

1. @Component取代<bean class="">

       @Component("id") 取代 <bean id="" class="">

2.web开发,提供3个@Component注解衍生注解(功能一样)取代<bean class="">

       @Repository :dao层

       @Service:service层

       @Controller:web层

3.依赖注入    ,给私有字段设置,也可以给setter方法设置

       普通值:@Value("")

       引用值:

              方式1:按照【类型】注入

                     @Autowired

              方式2:按照【名称】注入1

                     @Autowired

                     @Qualifier("名称")

              方式3:按照【名称】注入2

                     @Resource("名称")

4.生命周期

       初始化:@PostConstruct

       销毁:@PreDestroy

5.作用域

       @Scope("prototype") 多例

  

  

免责声明:文章转载自《Spring 1 控制反转、依赖注入》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇win 10 禁用后置摄像头Eclipse 配置SVN下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

实战角度比较EJB2和EJB3的架构异同

】     EJB编程模型的简化     首先,EJB3简化的一个主要表现是:在EJB3中,一个EJB不再象EJB2中需要两个接口一个Bean实现类,虽然我们以前使用JBuilder这样可视化开发工具自动生成了EJB2的这三个类,好像不觉得复杂,但是当EJB个数增加时,就显得累赘了。     简化后的EJB3的sessionBean依靠annotation...

【转】使用XFire+Spring构建Web Service

XFire是与Axis 2并列的新一代Web Service框架,通过提供简单的API支持Web Service各项标准协议,帮助你方便快速地开发Web Service应用。 相 对于Axis来说,目前XFire相对受欢迎,加上其提供了和Spring集成的支持,在目前的Web Service开源社区拥有众多的追随者。并且因为XFire为Spring提供的支...

[Java工程实践] 1.Java常用概念:Bean

一、Java Bean基本概念: 1、所有属性为private2、提供默认构造方法3、提供getter和setter4、实现serializable接口 作者:杨博链接:https://www.zhihu.com/question/19773379/answer/31625054来源:知乎著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。...

IBM MQ 集成CXF 发送JMS 消息

1.修改wsdl 协议类型为 jms 替换 <soap:binding style="document"transport="http://schemas.xmlsoap.org/soap/http"/>为 <soap:binding style="document"transport="http://cxf.apache.or...

spring的后置处理器——BeanPostProcessor以及spring的生命周期

后置处理器的调用时机 BeanPostProcessor是spring提供的接口,它有两个方法——postProcessBeforeInitialization、postProcessAfterInitialization。关于这两个方法的调用时机,可以参考spring源码注释。 /** * Apply this BeanPostProc...

spring+springmvc+mybatis xml配置文件

一、jdbc.properties 文件: driver=com.mysql.jdbc.Driverurl=jdbc:mysql://192.168.31.xxx:3306/abc?useUnicode=true&characterEncoding=utf-8&useSSL=falseusername=xxxpassword=xxx#定义初...