使用注解开发
8、使用注解开发
在spring4之后,使用注解开发,必须要保证aop包的导入
使用注解需要导入contex的约束
<?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>
8.1 bean
需要在配置中加入< context:component-scan>标签。有了< context:component-scan>,另一个< context:annotation-config/>标签可以移除掉,因为已经被包含进去了。
<!--指定要扫描的包,这个包下面的注解才会生效
别只扫一个com.xy.pojo包
这里也可以用空格扫描多个包
-->
<context:component-scan base-package="com.xy"/>
<context:annotation-config/>
@Component注解
//@Component 注解
//等价于<bean id="user" classs"com.xy.pojo.User"/>
@Component
public class User {
public String name ="xy";
}
8.2 属性注入 @value
@Component
public class User {
//相当于<property name="name" value="xy"/>
@value("xy")
public String name;
//也可以放在set方法上面
//@value("xy")
public void setName(String name) {
this.name = name;
}
}
8.3 衍生的注解
@Component有几个和它具有相同功能的衍生注解,会按照web开发中,mvc架构中分层。
- dao (@Repository)
- service(@Service)
- controller(@Controller)
这四个注解的功能是一样的,都是代表将某个类注册到容器中
8.4 自动装配注解
@Autowired(与@Qualifier搭配使用):默认是byType方式,如果匹配不上,就会byName
@Nullable:字段标记了这个注解,说明该字段可以为空
@Resource:默认是byName方式,如果匹配不上,就会byType
8.5 作用域@scope
//原型模式prototype,单例模式singleton
//scope("prototype")相当于<bean scope="prototype"></bean>
@Component
@scope("prototype")
public class User {
//相当于<property name="name" value="xy"/>
@value("xy")
public String name;
//也可以放在set方法上面
@value("xy")
public void setName(String name) {
this.name = name;
}
}
关于作用域的知识,回顾 [Bean作用域](##6.4 Bean作用域)
8.6 小结
xml与注解:
- xml更加万能,维护简单,适用于任何场合
- 注解,不是自己的类使用不了,维护复杂
最佳实践:
- xml用来管理bean
- 注解只用来完成属性的注入
- 要开启注解支持
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?