Spring的艺术(四):Spring5竟然可以彻底抛弃xml配置

听说微信搜索《Java鱼仔》会变更强哦!

本文收录于JavaStarter ,里面有我完整的Java系列文章,学习或面试都可以看看哦

(一)概述

前面看了这么多,不知道大家有没有这样一种感觉,如果每写一个对象都要去xml文件中定义这个bean,似乎依然还是很繁琐。Spring也考虑到了,因此在后续的Spring版本中,慢慢地开始用注解去代理xml文件配置。

(二)如何使用注解开发

首先肯定要把Spring系列的依赖先导入,前面也介绍了,只需要导入spring-webmvc的依赖,他就会自动将其他的依赖导入:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.9.RELEASE</version>
</dependency>

接着在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.javayz.pojo"/>
    <context:annotation-config/>
</beans>

然后就开始使用吧!
在pojo包下新建一个普通的实体类叫User

@Component
public class User {
    @Value("javayz")
    private String name;
    //省略get、set、toString方法
}

这里用到了两个注解,一个叫Component,这个注解相当于:

<bean id="user" class="com.javayz.pojo.User"/>

第二个注解叫Value,这个注解相当于:

<property name="name" value="javayz"/>

最后来测试一下:

public class Test {
    @org.junit.Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        User  user = (User) context.getBean("user");
        System.out.println(user);
    }
}

(三)更多的注解

@Component将一个类注入到Spring容器中,在实际的开发中,我们会用几个功能相同的注解来申明不同功能的类,比如:

当申明一个实体类时,我们会用@Repository

申明Service层的类时,用@Service

申明Controller层的类时,用@Controller

但是他们的功能都是一样的。

在配置文件中,我们通过scope来指定Bean的作用域,我们可以类上直接使用注解@Scope(“singleton”) 实现。

(四)彻底抛弃xml配置文件

在Spring5中,我们甚至可以不用去写xml配置文件,直接使用@Configuration注解完成和配置文件一样的功能。

在上面项目的基础上,删除xml配置文件,新建一个config包,并在这个包下新建一个SpringConfig,这个类的核心是@Configuration注解.

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

    @Bean(name = "user")
    public User getUser(){
        return new User();
    }
}

这段的代码和上面配置文件实现的功能完全一致。我最早学习Spring时还没有不写xml的方式,从这里也能看出Spring也在一步步减少繁琐的配置项。

测试一下,这里需要用到AnnotationConfigApplicationContext来获取配置类

@org.junit.Test
public void test2(){
    ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
    User user = (User) context.getBean("user");
    System.out.println(user);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java鱼仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值