Spring(五)注解开发

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第17天,点击查看活动详情

1.注解开发

为了简化配置,Spring支持使用注解代替xml配置。

和 XML 配置文件一样,注解本身并不能执行,注解本身仅仅只是做一个标记,具体的功能是框架检测到注解标记的位置,然后针对这个位置按照注解标记的功能来执行具体操作。

本质上:所有一切的操作都是 Java 代码来完成的,XML 和注解只是告诉框架中的 Java 代码如何执行。

2.Spring常用注解

2.0 注解开发准备工作

如果要使用注解开发必须要开启组件扫描,这样加了注解的类才会被识别出来。Spring才能去解析其中的注解。

<!--启动组件扫描,指定对应扫描的包路径,该包及其子包下所有的类都会被扫描,加载包含指定注解的类-->
<context:component-scan base-package="com.sangeng"/>
复制代码

2.1 IOC相关注解

2.1.1 @Component,@Controller,@Service ,@Repository

上述4个注解都是加到类上的。

他们都可以起到类似bean标签的作用。可以把加了该注解类的对象放入Spring容器中。

实际再使用时选择任意一个都可以。但是后3个注解是语义化注解。

如果是Service类要求使用@Service。

如果是Dao类要求使用@Repository

如果是Controllerl类(SpringMVC中会学习到)要求使用@Controller

扫描二维码关注公众号,回复: 13795651 查看本文章

如果是其他类可以使用@Component

例如:

配置文件如下:

<?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 http://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.sangeng"></context:component-scan>

</beans>
复制代码

类如下:

@Repository("userDao")
public class UserDaoImpl implements UserDao {

    public void show() {
        System.out.println("查询数据库,展示查询到的数据");
    }
}

复制代码
@Service("userService")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserServiceImpl implements UserService {


    private UserDao userDao;

    private int num;

    private String str;


    public void show() {
        userDao.show();
    }
}

复制代码

测试类如下:

public class Demo {
    public static void main(String[] args) {
        //创建容器
        ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        //获取对象
        UserDao userDao = (UserDao) app.getBean("userDao");
        Phone phone = (Phone) app.getBean("phone");
        UserService userService = (UserService) app.getBean("userService");
        System.out.println(phone);
        System.out.println(userService);
        System.out.println(userDao);
    }
}
复制代码

猜你喜欢

转载自juejin.im/post/7087432035026862111