Spring学习(二)

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

1、Bean的信息存放在applicationConfig.xml中  spring-mvc

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

2、bean的基本设置mvc

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

  id : 个人理解是一个bean有一个id,表明了这个bean,即惟一标识this

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

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

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

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

一、构造器注入:依赖于构造方法实现。咱们能够经过构造方法来建立类对象,Spring也能够采用反射方式创造对象。(bean中有class的路径) xml

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个呢?太复杂了。

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

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

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

 四、不一样的bean之间若是存在关系,就可互相引用

5、不经过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;

相关文章
相关标签/搜索