Spring使用纯注解实现零配置

本文探讨了Spring从XML配置到注解配置的转变,介绍了@Configuration、@ComponentScan、@Bean和@Scope注解的用法。通过实例展示了如何使用这些注解实现零XML配置。虽然注解配置简化了部分工作,但可能会导致配置分散,增加排错难度。因此,建议结合XML和注解进行开发,利用XML管理Bean,注解负责属性注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前的学习中一直都在围绕Spring的xml配置文件进行bean的管理…Spring4之后Config成为了Spring的核心功能,可以完全脱离xml配置文件以零配置的形式实现。

其实说是零配置,只是xml不再需要;通过注解 + Java代码的形式取代xml。

@Configuration注解

配置注解:加在一个类上表明这个类与类名xml配置文件有同样的效果!

//ABCD.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">
 
</beans>


@Configration
public class ABCD{
}

@ComponentScan注解

在没有完全脱离xml文件需要扫描注解时使用< context:component-scan / >扫描包下的所有注解,并且隐式的开启注解驱动支持。

组件扫描注解:加在使用了@Configration的类上,表名这个替代xml配置文件的工具类会进行扫描注解,等价于xml中的组件扫描标签

SpringUtil是一个代替xml的工具类,ComponentScan(“com.pojo”)扫描 "com.pojo"包下的所有注解。

@Configuration
@ComponentScan("com.pojo")
public class SpringUtil {
}

@Bean注解

Bean注解:用于创建bean对象,加在方法上;等价于xml中的< bean >标签,可以传入一些参数设置别名。

别名person,实体类是User。

@Bean("person")
public User getUser(){
    return new User();
}

@Scope注解

Scope注解:bean对象作用域,虽然Bean注解中使用new关键字来创建对象,给人的感觉不像是从IOC容器中获取对象;但是底层还是受到Scope注解的约束。

@Scope("singleton")			//单例,默认不写也是单例
@Scope("prototype")			//原型模式,多例
public class User {
}

测试

使用上面的配置注解,在加上一些基本注解就能实现脱离xml配置文件

1. 编写实体类

@Component("user")
@Scope("singleton")
public class User {

    @Value("薯条")
    private String name;

    public void speak(){
        System.out.println(name + ": 说话!");
    }
}

2. 编写配置工具

@Configuration
@ComponentScan("com.pojo")
public class SpringUtil {

    @Bean("person")
    public User getUser(){
        return new User();
    }

}

3. 测试
由于脱离了配置文件,无法使用ClassPathXmlApplicationContext加载,而由另外一个接口AnnotationConfigApplicationContext实现,传入工具类的class对象

public class SpringTest {

    @Test
    public void test1(){
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringUtil.class);
        User user1 = context.getBean("person", User.class);
        user1.speak();
        User user2 = context.getBean("person", User.class);
        System.out.println(user1.hashCode());
        System.out.println(user2.hashCode());
    }
}

在这里插入图片描述

总结

  1. 纯注解取代xml似乎看起来比较简单方便,实际上只是将配置文件中的标签零零散散的分布在各个类中,非常容易出现排错困难的情况,不推荐使用。

  2. xml配置文件虽然繁琐,但是管理方便一目了然。对于一些复杂的配置实现轻松;例如:扫描包的时候不使用默认的方式,需要加上过滤器,这时候注解的方式就显得费力!

  3. 推荐xml与注解整合开发:使用xml管理Bean,注解完成属性注入。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值