8.使用注解开发
8.使用注解开发
在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>"> <context:annotation-config/> //加入这行代码,不加注解不生效☆ </beans>
8.1.bean
8.2.属性如何注入
//等价于<bean id="name" class="com.itxiaofei.pojo.User"/> //@Component组件 @Component public class User { //相当于 <property name="name" value="小飞"/>,也可以放在set方法上 // 注意,简单的话用注解方便,多个类的话在配置文件里 // <bean id="name" class="com.itxiaofei.pojo.User"> // <property name="name" value="小飞"/> // </bean> @Value("小飞") public String name; }
8.3.衍生的注解
@Component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层!
- dao【@Repository】
- service【@Service】
- controller【@Controller】
- 小结:@Component、@Repository、@Service、@Controller这四个注解的功能都是一样的,都是代表将某个类注册到Spring容器中,装配。
8.4.自动装配装置
-@Autowired:自动装配通过类型,名字 -@nullable:字段标记了这个注解,说明这个字段可以为null。 -@Resource:自动装配通过名字,类型
8.5.作用域
@Scope
//单例模式(spring默认的,产生的都一样),类似于 //<bean id="name" class="com.itxiaofei.pojo.User" scope="singleton"/> @Scope("singleton") public class User { public String name; } //原型模式(每次从容器中get的时候都会产生新对象),类似于 //<bean id="name" class="com.itxiaofei.pojo.User" scope="prototype"/> @Scope("prototype") public class User { public String name; }
8.6.小结
xml与注解:
- xml更万能,使用于任何场合!维护简单方便
- 注解 不是自己的类使用不了,维护相对复杂!
xml与注解最佳实践:
- xml用来管理bean
- 注解只负责完成属性的注入
- 我们在使用过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持
<!--指定要扫描的包,这个包下的注解就会生效--> <!--注意:base-package="com.itxiaofei",让哪个包下的注解生效--> <context:component-scan base-package="com.itxiaofei"/> <!-- 加入这行代码,不加注解不生效☆--> <context:annotation-config/>
分类:
Spring学习笔记
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术