Spring 学习笔记(2)——自动装配

来源:互联网 发布:客户达装修软件 编辑:程序博客网 时间:2024/06/06 13:33

Spring 提供4种自动装配类型(autowire):

autowire 属性值:

no:默认值。Spring默认不进行自动装配,必须显示指定的依赖对象

byName:根据属性名自动装配。Spring自动查找与属性名相同的id,如果找到则自动注入,否则什么都不做

byType:根据属性的类型自动装配。Spring自动查找与属性类型相同的Bean,如果刚好找到唯一的那个,则自动注入;如果找到多个与属性类型相同的Bean,则抛出UnsatisfiedDependencyException异常;如果没找到,就什么也不做。

constructor:和byType类似,不过它针对构造方法。如果Spring找到一个Bean和构造方法的参数类型相匹配,则通过构造注入该依赖对象,如果找不到,将抛出异常(实验中,该处返回null)


在applicationContext.xml中的beans后加入default-autowire属性,从而设置全局自动装配。


注解:

1)引入命名空间  在applicationContext.xml 文件中的beans里

xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
2)注解解析器  

<context:annotation-config/>
3)自动装配方式

@Autowired           ——byType

@Autowired(required=false)          ——byType,可以为空

@Autowired@Qualifier("student")             ——byName

@Resource 默认按名称,找不到时按类型

@Resource(name="")        ——byName

全自动装配:

1)命名空间 (同上)

2)注解扫描器 (并且其下所有类自动装配)

<context:component-scan base-package="     " />
3)注解标识

@Repository    用于标识Dao类

@Service    用于标识业务类

@Controller   用于标识控制器类

@Component  用于标识例如实体类等的其他类


@Scope  用于标识单例模式或多例模式("singleton","prototype")






0 0
原创粉丝点击