Spring注解开发

一。使用注解开发

  1. 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
  • 注解用于注入属性
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值