一。使用注解开发
- 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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
//扫描指定包下注解
<context:component-scan base-package="di"></context:component-scan>
//启动注解
<context:annotation-config></context:annotation-config>
</beans>
2.bean
3.属性如何注入
//component相当于 <bean id="dog" class="di.Dog"></bean>
@Component
public class Dog {
//value相当于<property name="say" value="wang~"></property>
@Value("wang~")
private String say;
public String getSay() {
return say;
}
//在set方法上也可达到同样效果
@Value("wang~")
public void setSay(String say) {
this.say = say;
}
}
4.衍生的注解
@Component有几个衍生的注解,我们在Web开发中,Mvc三层架构
- dao : 【@Repository】
- service: 【@Service】
- Controller: 【@Controller】
这四个注解都是相同的意思,都是Spring中配置Bean的
5 自动装配
@AutoWired
@Qualifier(value = “”)
@Nullable 如果标记了这个注解,表示参数为空
6 作用域注解
@Scope(“singleton | prototype | request | session | application”)
7 小结
XML与注解
- XML更加万能,适用于任何情况,使用起来简单方便
- 注解 简单快捷,但局限性很大,维护起来困难
最佳实践
- XML用于配置Bean
- 注解用于注入属性