SSM-Spring-Spring装配Bean-通过注解装配Bean-使用@Component装配Bean

SSM-Spring-Spring装配Bean-通过注解装配Bean-使用@Component装配Bean

​ 使用这种方式可以减少XML的配置,注解功能更加强大,可以实现XML的功能,还有自动装配的功能。

​ 在Spring 中,提供两种方式让Spring IoC发现Bean:

  • 组件扫描:定义资源的方法,让容器扫描对应的包,从而把Bean装配进来。
  • 自动装配:通过注解定义,使得一些依赖可以通过注解完成

现在主流的方式是:以注解为主,XML方式为辅


使用@Component装配Bean

@Component(value = "Cat")
public class Cat {
    
    
    @Value("1")
    private int id;
    @Value("小强")
    private String name;
    @Value("黄色")
 	//set and get ...   
}

分析:

  1. @Component:代表Spring Ioc会把这个类扫描生成Bean实例,其中vlaue属性代表这个类在Spring中的id,如在XML中定义Bean的id,也可以简写@Component(“Cat”)或者不写,对于不写,容器会默认类名,以小写字母开头的方式作为id,配置到容器中
  2. @Value:代表值的注入,这里只是一些简单的注入

上面只是定义了一个Bean,还需要Spring Ioc通过扫描的方式找到该Bean:

package spring.pojo;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan
public class PojoConfig {
    
    
}

分析:

  1. 包名和POJO保持一致
  2. @ComponentScan:代表进行扫描,默认扫描当前包的路径,POJO的包名和它保持一致才能扫描,否则是没有的

还可以通过XML配置扫描

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       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/util  http://www.springframework.org/schema/beans/spring-util.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
	<!--在这里配置扫描内容,base-package是扫描的路径-->   
    <context:component-scan base-package="spring.pojo"></context:component-scan>
</beans>

使用context命名空间的component-scan配置扫描包的功能,base-package代表包的路径

下面是通过上面实现定义好Spring Ioc容器的实现类:

public class Text02 {
    
    
    public static void main(String[] args) {
    
    
        ApplicationContext context = new AnnotationConfigApplicationContext(PojoConfig.class);
        Cat bean = context.getBean(Cat.class);
        System.err.println(bean.getId());
    }
}
  • AnnotationConfigApplicationContext方法:去初始化Spring Ioc容器它的配置项是PojoConfig类,这样就会根据注解的配置去解析对应的资源,生成IOC容器

@ComponentScan两个配置:

  1. basePackages:由base 和Packages组成,这个属性可以配置一个java包的数组,Spring会根据它配置扫描对应的包和子包,将配置好的Bean装配进来
  2. basePackagesClasses:可以配置多个类,Spring根据配置的类所在的包,为包和子包进行扫描装配对应配置的Bean

猜你喜欢

转载自blog.csdn.net/weixin_43958223/article/details/115080396