第四节:如何使用注解方式从IOC中获取bean(自学Spring boot 3.x的第一天)

大家好,我是网创有方,上一节学习了如何理解Spring的两个特性IOC和AOP,这一节来基于上节的内容进行一个简单实践。这节要实现的效果是通过IOC容器获取到Bean,并且将Bean的属性显示打印出来。

第一步:创建pojo实体类student

新建一个pojo包,创建一个student实体类,通过右键Generate生成属性的getter和setter方法。

Student.java

复制代码
package cn.wcyf.wcai.pojo;

public class Student {

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    String  name;//姓名
    int age;//年龄
}

第二步:创建Appconfig容器配置类

新建一个config包,创建一个AppConfig.java类

新增代码如下:

复制代码
package cn.wcyf.wcai.config;

import cn.wcyf.wcai.pojo.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean(name = "student")
    Student initStudent(){
        Student student = new Student();
        student.setAge(18);
        student.setName("小明");
        return student;
    }
}

上面注意注解@Configuration表示这个是一个java配置类,后面会根据这个配置生成一个IOC容器。@Bean(name = "student") 前面的@Bean声明这个方法将会把bean装填到IOC容器中。

如果@Bean后面跟着name="student"意味着后面的生成的Student类对象是student,如果不声明的话,后面调用Student的类对象要使用initStudent。所以为了更方便,建议大家增加name。

第三步:创建IOC容器,加载bean到容器中

代码如下:

复制代码
@SpringBootApplication

public class WcaiApplication {


    public static void main(String[] args) {
        var ctx = new AnnotationConfigApplicationContext(AppConfig.class);//创建一个IOC容器
        var student = ctx.getBean(Student.class);//从容器中获取一个Student bean
        System.out.println(student.getName());
        System.out.println(student.getAge());
    }
    @Controller
    public static class HelloController {
        @GetMapping("/test")
        public String test(HttpServletRequest request) {

            return "index";
        }
    }


}

注意,这里使用了new AnnotationConfigApplicationContext(Appconfig.class)替代了默认的 SpringApplication.run(WcaiApplication.class, args);

第四步:运行看效果

参考:《深入浅出Spring-Boot-3.x》

《SpringBoot企业级应用开发》

相关推荐
MacroZheng2 分钟前
还在用WebSocket实现即时通讯?试试MQTT吧,真香!
java·spring boot·后端
稚辉君.MCA_P8_Java16 分钟前
豆包 Java的23种设计模式
java·linux·jvm·设计模式·kubernetes
tanyongxi6617 分钟前
C++ 特殊类设计与单例模式解析
java·开发语言·数据结构·c++·算法·单例模式
遗憾皆是温柔19 分钟前
24. 什么是不可变对象,好处是什么
java·开发语言·面试·学习方法
midsummer_woo25 分钟前
基于springboot的IT技术交流和分享平台的设计与实现(源码+论文)
java·spring boot·后端
Peter(阿斯拉)36 分钟前
[Java性能优化]_[时间优化]_[字符串拼接的多种方法性能分析]
java·性能优化·stringbuilder·string·字符串拼接·stringbuffer·时间优化
这里有鱼汤1 小时前
miniQMT+Qlib才是AI量化的正确打开方式
后端
无奈何杨1 小时前
风控系统事件分析中心,关联关系、排行、时间分布
前端·后端
Moment1 小时前
nginx 如何配置防止慢速攻击 🤔🤔🤔
前端·后端·nginx
rannn_1111 小时前
【MySQL学习|黑马笔记|Day7】触发器和锁(全局锁、表级锁、行级锁、)
笔记·后端·学习·mysql