Spring容器注解详解<四>

本文详细阐述了Spring容器注解的概念、用途、使用规则,并通过实例演示了@Resource注解的使用方法,以及与依赖注入的区别。此外,文章还介绍了类扫描注解解析器的功能,展示了依赖注入与注解之间的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题?spring容器注解是什么?有什么作用?它和依赖注入有什么不同?

一、定义

注解:

  1、注解就是为了说明java中的某一个部分的作用(Type)

   2、注解都可以用于哪个部门是@Target注解起的作用

  3、注解可以标注在ElementType枚举类所指定的位置上

  4

        @Documented    //该注解是否出现在帮助文档中

        @Retention(RetentionPolicy.RUNTIME)//该注解在java,class和运行时都起作用

        @Target(ElementType.ANNOTATION_TYPE)//该注解只能用于注解上

        public@interface Target {

             ElementType[] value();

         }

   5、用来解析注解的类成为注解解析器




@Resource注解的使用规则:

   1、在spring的配置文件中导入命名空间(下面三个,跟以往的配文件内容不同,要使用@Resouse注解,需要加上)

         xmlns:context="http://www.springframework.org/schema/context"

        http://www.springframework.org/schema/context

        http://www.springframework.org/schema/context/spring-context-2.5.xsd


   2、引入注解解析器(在配置文件中必须加上)

        <context:annotation-config></context:annotation-config>


   3、在spring的配置文件中把bean引入进来

   4、在一个类的属性上加

            @Resource(name="student_annotation")

            private Student student;


         从该注解本身(可点击进去@Resouse)

               @Target({TYPE, FIELD, METHOD})

               @Retention(RUNTIME)

               public @interface Resource {

                  String name() default"";

               }

           1、该注解可以用于属性上或者方法上,但是一般用于属性

           2、该注解有一个属性name,默认值为"",如果不写name的话就是默认值


   5、分析整个过程:

        1、当启动spring容器的时候,spring容器加载了配置文件

        2、在spring配置文件中,只要遇到bean的配置,就会为该bean创建对象

        3、在纳入spring容器的范围内查找所有的bean,看哪些bean的属性或者方法上加有@Resource

        4找到@Resource注解以后,判断该注解name的属性是否为""(name没有写)

              如果没有写name属性,则会让属性的名称的值和springID的值做匹配,如果匹配成功则赋值

                                       如果匹配不成功,则会按照类型进行匹配,如果匹配不成功,则报错

              如果有name属性,则会按照name属性的值和springbeanID进行匹配,匹配成功,则赋值,不成功则报错



案例:

package cn.itcast.sh.spring.di.annotation;


import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Person {
	private Long pid;
	private String pname;
	
	//在这里相当于注解了一个对象给了student
	@Resource(name="studentAnnotation")//下面两个注解就相当于这个一样。
//	@Autowired    //这个是按照类型进行匹配,在同一个配置文件中,不能出现两个类型的bean
//	@Qualifier("studentAnnotation")//这个和上一个一起用
	private Student student;
	
	
	private List lists;
	private Map map;
	private Properties properties;
	private Set sets;
	
	public void showStudent(){
		this.student.show();
	}
}



package cn.itcast.sh.spring.di.annotation;

public class Student {
	public void show(){
		System.out.println("sdsdsdsd");
	}
}

配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
	<!-- 注解解析器
		能够加注解解析器的只能是引用类型的,不能是基本类型的
	 -->
		<context:annotation-config></context:annotation-config>
	                
     <bean id="personAnnotation" class="cn.itcast.sh.spring.di.annotation.Person"></bean>
     
     <bean id="studentAnnotation" class="cn.itcast.sh.spring.di.annotation.Student"></bean>
</beans>

测试类:

package cn.itcast.sh.spring.ioc.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.itcast.sh.spring.di.annotation.Person;


public class SpringAnnotation {
	@Test
	public void A(){
		ApplicationContext applicationContext = new  ClassPathXmlApplicationContext("applicationContext.xml");
		Person person = (Person)applicationContext.getBean("personAnnotation");
		person.showStudent();
	}
}

结果:







类扫描的注解:

   1、在spring的配置文件中导入命名空间

         xmlns:context="http://www.springframework.org/schema/context"

        http://www.springframework.org/schema/context

        http://www.springframework.org/schema/context/spring-context-2.5.xsd

  2<context:component-scanbase-package="cn.itcast.annotation.scan"></context:component-scan>

       1、该注解解析器包含了两个功能:依赖注入和类扫描

       2、在base-package包及子包下查找所有的类

  3、如果一个类上加了@Component注解,就会进行如下的法则

        如果其value属性的值为""

              @Component

              public class Person {}

              ==

              <bean id="person"class="..Person">

       如果其value属性的值不为""

              @Component("p")

              public class Person {}

              ==

              <bean id="p"class="..Person">

  4、按照@Resource的法则再次进行操作


案例:

package cn.itcast.sh.spring.di.class_annotation;




import javax.annotation.Resource;

import org.springframework.stereotype.Component;

@Component("a")	
//相当于做了<bean id="a" class="....Person">
public class Person {
	
	//在这里相当于注解(引用了)了一个对象给了student
	@Resource(name="b")//下面两个注解就相当于这个一样。																																						
	private Student student;

	
	public void showStudent(){
		this.student.show();
	}
}


package cn.itcast.sh.spring.di.class_annotation;

import org.springframework.stereotype.Component;

@Component("b")
//相当于<bean id="b" class=".....Student"></bean>
public class Student {
	public void show(){
		System.out.println("sdsdsdsd");
	}
}

配置文件 :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
           
           <!-- 类扫描注解解析器
           component-scan:相当于一个对象类
           	base-package:需要扫描的包(包括下面的子包) 
           -->
        <context:component-scan base-package="cn.itcast.sh.spring.di.class_annotation"></context:component-scan>s
</beans>

测试类:

package cn.itcast.sh.spring.ioc.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.itcast.sh.spring.mvc.PersonAction;
import cn.itcast.sh.spring.util.SpringUtil;

public class MVCTest {
	@Test
	public void A(){
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		Person person = (Person)applicationContext.getBean("a");
<span style="white-space:pre">		</span>person.showStudent();
	
	}
}



依赖注入与注解的区别:


 作用:他们两个都是对spring容器中的对象类属性进行赋值.可以选择其中一种进行使用

  1依赖注入书写麻烦,但是效率高

  2、注解书写简单,但是效率低


依赖注入

@Resource

@Autowired

@Qualifier

类扫描

@Component

@Controller

@Repository

@Service


<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.5.4</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.mz</groupId> <artifactId>hejiayun-community</artifactId> <version>0.0.1-SNAPSHOT</version> <name>hejiayun-community</name> <packaging>jar</packaging> <description>合家云社区物业管理平台</description> <properties> <java.version>17</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <maven-jar-plugin.version>3.3.0</maven-jar-plugin.version> <druid.version>1.2.21</druid.version> <bitwalker.version>1.21</bitwalker.version> <fastjson.version>2.0.43</fastjson.version> <oshi.version>6.4.6</oshi.version> <jna.version>5.13.0</jna.version> <commons.fileupload.version>1.5</commons.fileupload.version> <poi.version>5.2.4</poi.version> <velocity.version>2.3</velocity.version> <jwt.version>0.12.3</jwt.version> <mybatis-plus.version>3.5.5</mybatis-plus.version> <easy-captcha.version>1.6.2</easy-captcha.version> <jsqlparser.version>4.5</jsqlparser.version> </properties> <dependencies> <!-- Spring Boot Web Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Boot AOP --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <!-- Spring Boot Validation --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <!-- Spring Boot DevTools --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <!-- MySQL Connector --> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> <!-- Druid Connection Pool --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-3-starter</artifactId> <version>${druid.version}</version> </dependency> <!-- MyBatis Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> <!-- <!– PageHelper –> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.4.7</version> </dependency>--> <!-- Redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <!-- FastJSON2 (替代FastJSON) --> <dependency> <groupId>com.alibaba.fastjson2</groupId> <artifactId>fastjson2</artifactId> <version>${fastjson.version}</version> </dependency> <!-- Jackson for JSON processing --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <!-- JWT Token --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>${jwt.version}</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>${jwt.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <version>${jwt.version}</version> <scope>runtime</scope> </dependency> <!-- System Information --> <dependency> <groupId>com.github.oshi</groupId> <artifactId>oshi-core</artifactId> <version>${oshi.version}</version> </dependency> <dependency> <groupId>net.java.dev.jna</groupId> <artifactId>jna</artifactId> <version>${jna.version}</version> </dependency> <dependency> <groupId>net.java.dev.jna</groupId> <artifactId>jna-platform</artifactId> <version>${jna.version}</version> </dependency> <!-- User Agent Utils --> <dependency> <groupId>eu.bitwalker</groupId> <artifactId>UserAgentUtils</artifactId> <version>${bitwalker.version}</version> </dependency> <!-- Captcha --> <dependency> <groupId>com.github.whvcse</groupId> <artifactId>easy-captcha</artifactId> <version>${easy-captcha.version}</version> </dependency> <!-- Spring Boot Logging --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </dependency> <!-- Test Dependencies --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <!-- Spring Security (如果需要,取消注释) --> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> --> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </exclude> </excludes> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>17</source> <target>17</target> </configuration> </plugin> </plugins> </build> </project>看看我的配置文件
最新发布
07-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值