使用注解开发

  • 在Spring4之后,要使用注解开发,必须要保证aop的包导入了
  • 使用注解需要导入context约束,增加注解的支持

通过一个小deemo解释,结构如图所示
5KoBnDQDAJ.png!large

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
        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:component-scan base-package="com.hudu"/>
    <context:annotation-config/>

<!--    <bean id="user" class="com.com.hudu.pojo.User">-->
<!--        <property name="name" value="hudu"/>-->
<!--    </bean>-->

</beans>

使用注解开发,实体类配置如下所示

//等价于<bean id="user" class="com.com.hudu.pojo.User"/>
//@Component 组件
@Component
@Scope("singleton")
public class User {
    //相当于<property name="name" value="hudu"/>,或者再set方法上
    @Value("hudu")
    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

测试类

public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = context.getBean("user", User.class);
        System.out.println(user.name);
    }
@Autowired:自动装配类型,名字。如果Autowried不能唯一自动装配上属性,则需要通过@Qualifier(value="xxx")
@Nullable:字段标记了这个注解,说明这个字段可以为null
@Resource:自动装配,通过名字,再通过类型
@Component:组件,放在类型,说明这个类被Spring管理了,就是bean。下面是Component的衍生注解,我们再我们在web开发中,会按照mvc三层架构分层!
dao:@Repository
service:@Service
controller:@Controller 这四个注解功能一样,都是代表将某个类注册到Spring中,装配bean

小结

xml与注解:

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

xml与注解的最佳实践:

  • xml用来管理bean
  • 注解只负责完成属性的注入
  • 我们在使用的过程中只需要注意一个问题,必须让注解生效,就需要开启注解的支持
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.hudu"/>
<context:annotation-config/>
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
247
粉丝
17
喜欢
213
收藏
58
排名:732
访问:9674
私信
所有博文
社区赞助商