Spring学习(二)

前言:从上一节我们知道Spring IoC主要是通过配置文件或者注解的方式并通过第三方去生成或获取特定的对象。 Bean可以理解为类的代理。

一、Bean的信息存放在applicationConfig.xml中  

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

    <bean class="">
        <property "/> //类的属性
        ....       
    </bean>
</beans>

二、bean的基本设置

  <bean id =" "  class = " "   scope=“ ” />

  id : 我的理解是一个bean有一个id,代表了这个bean,即唯一标识

  class : Java类的具体路径,描述哪个类,就填入那个类的路径

  scope :Bean的作用范围-->(1)singleton:默认的,Spring会采用单例模式创建这个对象

                (2)  prototype: 多例模式。(Struts2和Spring整合一定会用到)

三、定义了这些bean,怎么注入到IoC容器中呢?三种方式

1、构造器注入:依赖于构造方法实现。我们可以通过构造方法来创建类对象,Spring也可以采用反射方式创造对象。(bean中有class的路径) 

public class User {
    private int id;
    private String username;
           
    public User(int id,String username){
        this.id = id;
        this.username = username;        
    }
}
//对应的bean
<bean id="user1" class="com.dongtian.po.User">
  <constructor-arg index = "0" value = "1"/> //index = 0 表示第一个参数,value = "1" --->id = 1
  
<constructor-arg index = "1" value = "张三"/>

</bean>

  缺点很明显,一个参数对应一个标签,如果有100个呢?太复杂了。

2、使用setter注入:主流方式  

<bean id="user2" class="com.dongtian.po.User">
   <property name="id" value="2" /> 
    <property name="username" value="李四" /> //如果是类型,value变为ref 
</bean>

 3、接口注入方式:获取外界资源

 4、不同的bean之间如果存在关系,就可互相引用

五、不通过XML文件,也可以通过注解方式装载Bean 

@Component(value = "user")
public
class User {
  @Value("1")
private int id;
  @Value("张三")
private String username; public User(int id,String username){ this.id = id; this.username = username; } }

@Component : 表示把这个类扫描为Bean实例,value的值即是id

@Value :表示值的注入

 

有了这个类,还需要添加一个扫描器让IoC知道去哪里扫描对象:@ComponentScan

还有一个就是属性注入:@Autowired,也可以注解方法

@Autowired

private User user = null;

  

  

posted @ 2019-05-05 14:30  DongTian  阅读(166)  评论(0编辑  收藏  举报