spring注解驱动开发笔记(二)

上一次我介绍了如何使用纯注解开发来给ioc容器注入beanspring注解驱动开发笔记_rslly的博客-CSDN博客

 

这次我要介绍的是如何打印ioc容器中所有的bean的名称,这对开发调试非常有帮助,并且通过纯注解形式启动包扫描,把@controller@service@component这些注解的bean加载进ioc容器。

首先是打印ioc容器中的所有的bean的名称。

public class main {
    public static void main(String []args) {
        //加载xml文件,获取容器中的对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml");
        Person person = (Person) ac.getBean("person");
        System.out.println(person.getWeight());
        //加载配置类,获取容器中的对象
        AnnotationConfigApplicationContext ac2= new AnnotationConfigApplicationContext(config.class);
        Person person1 =(Person) ac2.getBean("person");
        System.out.println(person1.getWeight());
        var s = ac2.getBeanDefinitionNames();
        for (String s1:s){
            System.out.println(s1);
        }
    }
}

我使用了类型推断,这是java10的特性,java8无法正常编译,这个大家自行搜索,这里不是重点。

打印出来了,除了spring容器自身的bean就是自己注入的bean。 

我们还是像上次那样先用xml文件进行扫描。

我们先写一个test类,使用了@service注解。

package top.rslly;

import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

@Service
public class test {
}

比较简单,只需要加上一行配置就行。但是从springboot开始我们就致力于消除配置文件,因为大量的xml文件,可读性可想而知。

<?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">
    <bean name="person" class="top.rslly.Person">

        <constructor-arg name ="weight" value="100"/>
        <constructor-arg name = "leg" value="2"/>
    </bean>
    <context:component-scan base-package="top.rslly"/>
</beans>

那如何使用注解进行包扫描呢?

很简单,可以用@componentscan。

package top.rslly;

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

@Configuration
@ComponentScan(value = "top.rslly")
public class config {
    @Bean
    Person person (){
        return new Person(150,2);
    }
}

结果如下图。

容器中顺利注入了test类。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值