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

大家好,我是网创有方,上节我们实践了通过@Bean方式声明Bean配置。咱们这节通过@Component和@ComponentScan方式实现一个同样功能。这节实现的效果是从IOC中加载Bean对象,并且将Bean的属性打印到控制台。

第一步:创建pojo实体类student

上节我们是新建了一个config的包和pojo包,我们的student类放在pojo类中,这节要把student类移动到config中。为什么要移动,原因是@ComponentScan注解的类只会扫描当前包下的类,首先,创建一个student实体类,通过右键Generate生成属性的getter和setter方法。

Student.java

代码如下:

package cn.wcyf.wcai.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("student")
public class Student {
    @Value("小明")
    String  name;//姓名
    @Value("18")
    int age;//年龄

    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;
    }

}

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

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

package cn.wcyf.wcai.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class AppConfig {


}

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

代码如下:

@SpringBootApplication

public class WcaiApplication {


    public static void main(String[] args) {
        var ctx = new AnnotationConfigApplicationContext(AppConfig.class);
        var student = ctx.getBean(Student.class);
        System.out.println(student.getName());
        System.out.println(student.getAge());
    }
    @Controller
    public static class HelloController {
        @GetMapping("/test")
        public String test(HttpServletRequest request) {

            return "index";
        }
    }


}

第四步:运行看效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Mero技术博客

创作不易,打赏小弟可否

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

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

打赏作者

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

抵扣说明:

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

余额充值