使用注解开发
配置文件:
1 2 3 4 5 6 7 8 9 10 11 12
| <?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
|
一.使用注解实现自动装配
1.注解:Autowired
可以直接在setter或着属性上使用;
1 2
| @Autowired(required="true") @Qualifier(value = "address2")
|
使用这个注解的话,可以不用写setter方法;它会在bena中寻找符合命名规范的byTypee属性;如果命名找到的不止一个,它就会去找寻id一样的;**==如果类名也找不到,你又想自动装配的话,就可以使用@Qualifier 默认的配置自动装配的名字,通过id==**
2.注解:@Resource()
resource里面有两个属性,type和name;就是byname和bytype的区别;默认的是使用byName,找不到再用byType
3.注解:@Nullable
字段被这个标记的话,就可以为空,且不会报错;
二.使用注解开发
配置文件:
1 2 3 4 5 6 7 8 9 10 11 12 13
| <?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.saxon.Dao"/> <context:annotation-config/> </beans>
|
使用注解开发的第一步就是导入支持;
1 2
| <context:component-scan base-package="com.saxon.Dao"/>//扫描包里面的所有注解 <context:annotation-config/>//支持注解开发
|
1.@Component
就是把我们的类放到spring中进行一个托管;相当于下面的语句:
1
| <bean id="user" class="com.saxon.Dao.User"></bean>
|
它还可以根据类在不同的层次中位置进行一个划分,但是实际作用一样;
- @Repository Dao层
- @Service service层
- @Controller servlet层
2.@Value (“value”)
给对象属性赋值;
1 2 3 4 5 6
| @Controller public class User { @Value ("saxon1") public String name;
}
|
3.自动装配
在上面的笔记上有;
4.bean作用域
就是第七节讲的那个,只不过现在在类上配置;
1 2 3 4 5 6 7
| @Controller @Scope("singleton"||"prototype") public class User { @Value ("saxon1") public String name;
}
|
5.小结
xml:万能,什么都可以设置,维护简单,快捷;
注解:简单,但是不是自己的类,别人引用不了例如:ref
所以:==注解一般用来赋值,xml一般用来管理bean==