【Spring Framework】8、使用注解开发

使用注解开发

在Spring4之后,要使用注解开发,必须要保证 aop 的包导入了

image

使用注解需要导入 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
        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:annotation-config/>

</beans>

指定要扫描的包,这个包下面的注解才会生效

<context:component-scan base-package="com.xg"/>

image

1、bean

@Controller :组件,放在类上,说明这个类被Spring 管理了,就是bean,id默认类名小写,byName

applicationContext.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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    
    <!--指定要扫描的包,这个包下面的注解才会生效-->
    <context:component-scan base-package="com.xg"/>
    <context:annotation-config/>

</beans>

User

package com.xg.pojo;

import org.springframework.stereotype.Controller;

// 等价于    <bean id="user" class="com.xg.pojo.User"/>
@Component
public class User {
    public  String name = "遇见星光";
}

2、属性如何注入

@Value("value") :给字段赋值

package com.xg.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;

@Controller
public class User {
    // 相当于 <property name="name" value="遇见星光"/>
    @Value("遇见星光")
    public String name;
}

3、衍生注解

@Component有几个衍生注解,在web开发中,会按照MVC三层架构分层!

  • dao :【@Repository】
  • service :【@Service】
  • controller : 【@Controller】

四个注解功能一样,都是将某个类注册到Spring中,装配Bean

4、自动装配注解

@Autowired 直接在属性上使用即可!也可以在Set方法上使用!

使用 @Qualifier(value="xxx") 配合 @Autowired 使用

@Nullable // 字段标记了这个注解,说明这个字段可以为null

5、作用域

在类上使用

@Scope("singleton")
@Scope("prototype")

6、小结

XMl与注解:

  • xml :更加万能,适用于任何场合!维护简单方便
  • 注解 :不是自己类不能使用,维护相对复杂!

XMl与注解的最佳实践:

  • xml 用来管理bean
  • 注解只负责属性的注入!
posted @   遇见星光  阅读(60)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示