Spring注解开发
一、配置命名空间
1 2 3 4 5 6 7 8 9 | <? 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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 约束路径 -- > <!--配置组件扫描--> < context:component-scan base-package="com.finnlee" ></ context:component-scan > <!-- Spring容器加载properties文件 --> < context:property-placeholder location="xx.properties"/> < property name="" value="${key}"/></ beans > |
二、注解(必须配置组件扫描)
@Component:使用在类上用于实例化Bean 等价于 <bean id="userDao" class="com.finnlee.daoImpl.UserDaoImpl" ></bean>
@Autowired :使用在字段上用于根据类型依赖注入 (如果不加@Qualifier)
@Qualifier: 结合@Autowired一起使用用于根据名称进行依赖注入 (按照名称注入)
等价于
1 2 3 | < bean id="userService" class="com.finnlee.services.UserServiceImpl"> < property name="userDao" ref="userDao" ></ property > </ bean > |
@Resource : 相当于@Autowired+@Qualifier,按照名称进行注入 @Resource(name = "userDao")
@Controller : 使用在web层类上用于实例化Bean 和 @Component 一样
@Service : 使用在service层类上用于实例化Bean 和 @Component 一样
@Repository : 使用在dao层类上用于实例化Bean 和 @Component 一样
@Value : 注入普通属性 可以用来获取容器中的key值
@Scope : 标注Bean的作用范围
@PostConstruct:使用在方法上标注该方法是Bean的初始化方法 等价于 init-method
@PreDestroy : 使用在方法上标注该方法是Bean的销毁方法 等价于 destroy-method
新注解:
@Configuration : 用于指定当前类是一个 Spring 配置类,当创建容器时会从该类上加载注解
@ComponentScan : 用于指定 Spring 在初始化容器时要扫描的包。等价于 <context:component-scan base-package="com.itheima"/>
@Bean : 使用在方法上,标注将该方法的返回值存储到 Spring 容器中
@PropertySource : 用于加载.properties 文件中的配置
@Import : 用于导入其他配置类
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)