spring使用注解开发
在spring4之后,想要使用注解形式,必须引入aop的包
在配置文件中,还要引入一个context约束
<?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">
</beans>
1、配置扫描哪些包下的注解
<context:component-scan base-package="com.lili.entity"/>
2、开启对注解的支持
<context:annotation-config/>
Bean的实现:(@Component注解)
@Component
public class Address {
private String address;
// get,set,toString
}
@Component("student")
public class Student {
private String name;
private Address address;
// get,set,toString
}
属性注入:(也可以在set方法上)
@Component
public class Address {
@Value("china")
private String address;
// get,set,toString
}
衍生注解:
@Component:三个衍生注解
为了更好的进行分层,Spring可以使用其它三个注解,功能一样,目前使用哪一个功能都一样。
-
@Controller:web层
-
@Service:service层
-
@Repository:dao层
写上这些注解,就相当于将这个类交给Spring管理装配了!
自动装配注解(@Autowired):
@Component("student")
public class Student {
@Value("qijingjing")
private String name;
@Autowired
private Address address;
// get,set,toString
}
作用域:
@scope
-
singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁。
-
prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收
@Component
@Scope("prototype")
public class Address {
private String address;
// get,set,toString
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!