spring 注解注入方式

本文详细介绍了Spring框架中的注解配置方法及基本注解应用,包括组件扫描、简单注解示例和常见注解的区别。还讨论了复杂属性注入的不同方式,如Spring 2.5规范、JSR-250和JSR-443标准下的实现。通过实例解释了如何在实际项目中灵活运用这些注解,为开发者提供了一套高效、简洁的配置和调用方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[size=x-large][color=darkred]1.xml配置开启注解[/color][/size]

<?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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<!-- 注解 -->
<context:component-scan base-package="com.sxh.spring.annotaion"/>
</beans>

[size=x-large][color=darkred]2.简单的注解例子[/color][/size]

@Component("customerService")
//相当于<bean id="customerService"...>
public class CustomerService {
@Value("lisi")
//相当于<property name="name" value="lisi">
private String name;
public void list(){
System.out.println("name:"+name);
System.out.println("service list()...");
}
}

[size=x-large][color=darkred]3.框架常用注解(和上面@Component功能相同,区分层次)[/color][/size]

@Controller--Action
@Service--Service
@Repository--Dao


[size=x-large][color=darkred]4.复杂属性注入[/color][/size]

//方式1:spring2.5规范
@Autowired
@Qualifier("customerDao1")
private CustomerDao customerDao1;

//方式2:JSR-250,需要配置<context:annotation-config/>
//<!-- 使@Resource,@PostConstruct,@PreDestory,@Autowired 生效 -->
@Resource(name="customerDao2")
private CustomerDao customerDao2;

//方式3:JSR-443,需要javax.inject-1.jar
@Inject
@Named("customerDao3")
private CustomerDao customerDao3;


[size=x-large][color=darkred][/color][/size]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值