spring之(纯)注解开发

568 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

在使用讲xml配置文件开发的时候,我们会先写新建一个spring的xml配置文件,在里面写好自己要管理的对象的bean,写一下bean之间的依赖关系等等。但是到了spring注解开发阶段,这些配置都不用写,毫不夸张的说,你不再需要那个xml文件了。你现在可能带着很多疑问,不用xml配置,那如何实现呢。不要急,慢慢往下看。👇👇👇

自动扫描包下的注解

我们先按xml配置文件的方式入手,新建一个xml文件,如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      <!--step1-->
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       h
       <!--step2-->">
</beans>

在step1和step2处分别加入下面的代码 xmlns:context="http://www.springframework.org/schema/context"

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

加载包下注解扫描的配置,可以扫瞄com.spring2下面的所有注解。

<!--扫描该包下面的注解-->
<context:component-scan base-package="com.spring2"/>
<!--扫描propertise文件-->
<context:property-placeholder location="test.properties"/>

那扫描什么注解呢?看下面的代码

@Component("bookService")
public class BookServiceImpl implements BookService {
    //依赖bookdao
    @Autowired
    @Qualifier("bookDao")
    private BookDao bookDao;
    //注入简单类型
    //@Value("bookdao1")
    @Value("${name}")
    private String name;
    @Override
    public void save() {
        System.out.println("book service save..."+name);
        bookDao.save();
    }
}

上述代码中Component注解就是把BookServiceImpl这个类放入IoC容器中管理,相当于之前xml开发中的bean标签了就,参数可写可不写。
Autowired这个注解就是自动注入依赖,上述类依赖BookDao这个对象,加入这个注解,自动就DI(注入依赖)了,要注入哪一个bean也可以指定,就是下面的这个Qualifier这个注解了,参数就是指定某个bean的意思。@Value是注入简单类型的注解,要了解这些注解的含义,大家可以自己去查一查手册。现在大家应该知道自动扫描注解是扫描的什么了吧。 讲到这里还不算纯注解开发,我们会发现我们还是写了配置文件。

java类代替spring核心配置文件

@Configuration
public class SpringConfig {
}

我们可以使用java类来代替spring核心配置文件,spring提供了@Configuration注解来表示一个配置类,现在xml中就剩下这些东西了。

    <!--扫描该包下面的注解-->
    <context:component-scan base-package="com.itheima"/>

spring又提供了 @ComponentScan("com.itheima")这个注解来代替扫描注解的配置。 现在我们的xml里面东西都没有了,我们可以根据下面的测试方法来做测试。

public class App {
    public static void main(String[] args) {
        //ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookService bookService;
        try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class)) {
            BookDao bookDao = (BookDao) ctx.getBean("bookDao");
            //按类型获取bean,但要确保该类型但bean唯一
            bookService = ctx.getBean(BookService.class);
            DataSource dataSource = (DataSource) ctx.getBean("dataSource");
            System.out.println(dataSource);
        }
        bookService.save();

    }
}

这里和之前xml配置文件获取bean的测试方法一样,唯一不同的就是之前是获取配置文件,现在是获取配置类。之前,那个代码换成了这个而已。 AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class)
这就是本文要讲的spring纯注解开发了,是不是比xml配置文件开发方便太多了。