8 使用注解开发

2023-03-29  本文已影响0人  Messix_1102

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


maven截图

使用注解要导入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>

1 bean
2 属性如何注入

package com.hunter.pojo;

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

// 等价于<bean id="user" class="com.hunter.pojo.User"></bean>
@Component // 组件
public class User {
    // 等价于<property name="name" value="hunter"></property>
    // 也可以放到set方法上面
    @Value("hunter")
    public String name;
}

3 衍生的注解

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

  • dao 【@Repository】
  • service 【@Service】
  • controller 【@Controller】
    这四个注解功能是一样的,都是将被注解的类注入到Spring 容器中,装配bean

4 自动装配

  • @Autowired: 自动装配通过类型、名字
    如果 @Autowired 不能唯一装配上属性,则需要通过 @Qualifier(value=XXX) 指定
  • @Resource: 自动装配通过名字、类型
    如果 @Resource 不能唯一装配上属性,则需要通过 @Resource(name=XXX) 指定
  • @Nullable: 字段标记了这个注解,说明这个字段可以为null

5 作用域

@Scope("singleton")
public class User {
...

6 小结
xml 与注解:

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

最佳实践:

  • xml用来管理bean
  • 注解只负责完成属性的注入
  • 我们在使用的过程中,只需要注意一个问题,必须要注解生效就要开启注解支持
    <context:component-scan base-package="com.hunter"/>
    <context:annotation-config/>
上一篇 下一篇

猜你喜欢

热点阅读