【关于Spring那些事】——SpringIoC基于注解的配置


前言

在Spring容器中我们可以使用XML配置实现Bean的装配,但是如果Bean过多,则会显得XML文件过于臃肿,为后续的工作造成了一定的困难,因此Spring提供了一种基于注解(Annotation)的装配方式。


1.Spring配置文件

因为Spring容器初始化时,只会加载applicationContext.xml文件,那么我们在实体类中添加的注解就不会被Spring扫描,所以我们需要在applicationContext.xml声明Spring的扫描范围,以达到Spring初始化时扫描带有注解的实体类并完成初始化工作

在配置applicationContext.xml想要使用context标签声明注解配置需要在原来配置的基础上加context命名空间及相对应的约束。

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
    
    <!--声明使用注解配置,即开启注解处理器-->
    <context:annotation-config/>
    <!--声明Spring工厂注解的扫描范围-->
    <context:component-scan base-package="com.gyh.ioc.pojo"/>
    
</beans>

2.IoC常用注解

@Component

1.@Component:类注解,在实体类的位置加该注解,就表示将该实体类交给Spring容器管理,与bean作用相同。

2.@Component(value = “student”):value属性用来指定当前bean的id,相当于bean的id,value也可以省略,这时候id的值默认为将类名的首字母小写。(如:Student类首字母小写为student)

3.与@Component功能相同的注解还有@Controller、@Service、@Repository

  • @Controller注解 主要声明将控制器类交给Spring容器管理(控制层)
  • @Service注解 主要声明将业务处理类交给Spring容器管理(Service层)
  • @Repository注解 主要声明持久化类交给Spring容器管理(DAO层)
  • @Component 可以作用任何层次

@Scope

1.@Scope:类注解,声明当前类是单例模式还是原型模式,与bean标签中的scope属性作用相同。

2.@Scope(value = “prototype”)表示当前类是原型模式,不加value则默认为单例模式

@Lazy

1.@Lazy:类注解,用于声明一个单例模式的bean属于饿汉式还是懒汉式。

2.@Lazy(false):表示当前属于bean是饿汉式,不添加值则默认为懒汉式。

@PostConstruct@PreDestroy

1.@PostConstruct:方法注解,声明一个方法为当前类的初始化方法,与bean标签的init-method属性作用相同,在构造方法执行后调用。

@PostConstruct
public void init(){
    
    
    System.out.println("执行init方法!!!");
}

2.@PreDestroy:方法注解,声明一个方法为当前类的销毁方法,与bean标签的destroy-method属性作用相同,在Spring容器关闭时自动调用。

@PreDestroy
public void destroy(){
    
    
    System.out.println("执行destroy方法!!!");
}

@Autowired

1.@Autowired:属性注解、方法注解(setter方法),用于声明当前属性自动装配,默认byType。

2.@Autowired(required = false):表示如果找不到与属性类型相匹配的类也不抛异常,而是给null。(默认为required = true 抛出异常)

@Qualifier

1.@Qualifier:与@Autowired配合使用,会将默认的按Bean类型装配改为按Bean的实例名称装配,Bean的实例名称则由@Qualifier属性指定,如下:

@Autowired(required = false)
public void setBook(@Qualifier("book1") Book book) {
    
    
    this.book = book;
}

@Resource

1.@Resource:属性注解,用于声明自动装配,先按照byName查找,找不到之后按byType查找;如果都找不到或找到多个则抛出异常。


总结

这篇博客主要介绍了基于注解开发所常用的注解以及功能,希望可以帮到大家!

猜你喜欢

转载自blog.csdn.net/weixin_52986315/article/details/124206275