@Controller注解

86 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第19天,点击查看活动详

大家好,我是bug郭,一名双非科班的在校大学生。对C/JAVA、数据结构、Spring系列框架、Linux及MySql、算法等领域感兴趣,喜欢将所学知识写成博客记录下来。 希望该文章对你有所帮助!如果有错误请大佬们指正!共同学习交流

作者简介:

前情提要

我们上节内容学习了如何创建\注册\读取bean 我们发现bean对象操作十分的繁琐! 所以我们这个章节,就带大家来了解更加简单的bean操作,通过Spring下的注解来实现!

配置spring-config文件

我们之前注册bean是通过在xml配置文件中,通过键值对的方式注册bean对象! 显然这种方式很麻烦,注册一个对象,就要添加一项! 有没有什么好的方式可以让spring直接去注册对象! yes!

我们可以直接在配置文件配置好 spring下你要注册对象的包时那个! 当spring启动后,spring就会将bean对象自动注册!

  • spring-config配置文件
<?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:content="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">
       <!--在com包下扫描bean注册-->
        <content:component-scan base-package="com"></content:component-scan>
</beans>

当然只有一个配置文件显然不够嘛! 我们如何知道我们代码中的对象是bean对象捏? 这就要引入spring五大注解概念了! 我们通过在我们创建好的对象上面添加注解的方式,就是告诉spring这个对象需要注册到容器中!

类注解和方法注解

类注解:

  • @Controller
  • @Service
  • @Repository
  • @Component
  • @Configuration

方法注解: @Bean

我们可以通过上述两种注解将对象存储到Spring中!

@Controller(控制器存储)

使用@Controller注解存储bean

package com;
import org.springframework.stereotype.Controller;
@Controller //通过Controller注解存储bean对象
public class UserController {
    public void sayHi(){
        System.out.println("hello Controller注解!");;
    }
}

我们通过在UserController类上加上spring类注解,即可完成注册对象!

  • 在启动类中读取bean对象即可!
//启动类
public class app{
    public static void main(String[] args) {
        //1.获取上下文对象
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        //读取bean对象!
        UserController userController =
                (UserController) context.getBean("userController");
        //使用
        userController.sayHi();
    }
}

在这里插入图片描述 如果我们的需要注册的bean对象不在扫描包下,是否又能注册成功呢?

我们在新建一个controller包在其下创建TestController类,并且通过@Controller注册到Spring中!

package controller;
import org.springframework.stereotype.Controller;
@Controller //注册到Spring中!
public class TestController {
    public void sayHi(){
        System.out.println("该bean不在扫描的包下");
    }
}

然后我们通过ApplicationContext上下文对象读取bean 在这里插入图片描述 可以看到出现异常未找到名为textControllerbean对象!

结论:只有在扫描包下的类才能被Spring注册