Spring IOC基于XML和注解管理Bean(一)
文章目录
2.9、实验八:p命名空间
引入p命名空间
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:util="http://www.springframework.org/schema/util"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
引入p命名空间后,可以通过以下方式为bean的各个属性赋值
<beanid="studentSix"class="org.example.bean.Student"p:id="1006"p:name="小明"p:clazz-ref="clazzOne"p:teacherMap-ref="teacherMap"></bean>
2.10、实验九:引入外部属性文件
①加入依赖
<!-- MySQL驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.30</version></dependency><!-- 数据源 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.15</version></dependency>
②创建外部属性文件
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EEZ1sTcC-1686469380998)(img/2023-05-25-21-43-05.png)]
jdbc.user=root
jdbc.password=123456
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.driver=com.mysql.cj.jdbc.Driver
③引入属性文件
引入context 名称空间
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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
http://www.springframework.org/schema/context/spring-context.xsd"></beans>
<!-- 引入外部属性文件 --><context:property-placeholderlocation="classpath:jdbc.properties"/>
注意:在使用
<context:property-placeholder>
元素加载外包配置文件功能前,首先需要在 XML 配置的一级标签
<beans>
中添加 context 相关的约束。
④配置bean
<beanid="druidDataSource"class="com.alibaba.druid.pool.DruidDataSource"><propertyname="url"value="${jdbc.url}"/><propertyname="driverClassName"value="${jdbc.driver}"/><propertyname="username"value="${jdbc.user}"/><propertyname="password"value="${jdbc.password}"/></bean>
⑤测试
@TestpublicvoidtestDataSource()throwsSQLException{ApplicationContext ac =newClassPathXmlApplicationContext("spring-datasource.xml");DataSource dataSource = ac.getBean(DataSource.class);Connection connection = dataSource.getConnection();System.out.println(connection);}
2.11、实验十:bean的作用域
①概念
在Spring中可以通过配置bean标签的
scope
属性来指定bean的作用域范围,各取值含义参加下表:
取值含义创建对象的时机singleton(默认)在IOC容器中,这个bean的对象始终为单实例IOC容器初始化时prototype这个bean在IOC容器中有多个实例获取bean时
如果是在WebApplicationContext环境下还会有另外几个作用域(但不常用):
取值含义request在一个请求范围内有效session在一个会话范围内有效
②创建类User
packageorg.example.bean;publicclassUser{privateInteger id;privateString username;privateString password;privateInteger age;publicUser(){}publicUser(Integer id,String username,String password,Integer age){this.id = id;this.username = username;this.password = password;this.age = age;}publicIntegergetId(){return id;}publicvoidsetId(Integer id){this.id = id;}publicStringgetUsername(){return username;}publicvoidsetUsername(String username){this.username = username;}publicStringgetPassword(){return password;}publicvoidsetPassword(String password){this.password = password;}publicIntegergetAge(){return age;}publicvoidsetAge(Integer age){this.age = age;}@OverridepublicStringtoString(){return"User{"+"id="+ id +", username='"+ username +'\''+", password='"+ password +'\''+", age="+ age +'}';}}
③配置bean
<!-- scope属性:取值singleton(默认值),bean在IOC容器中只有一个实例,IOC容器初始化时创建对象 --><!-- scope属性:取值prototype,bean在IOC容器中可以有多个实例,getBean()时创建对象 --><beanclass="org.example.bean.User"scope="prototype"></bean>
④测试
@TestpublicvoidtestBeanScope(){ApplicationContext ac =newClassPathXmlApplicationContext("spring-scope.xml");User user1 = ac.getBean(User.class);User user2 = ac.getBean(User.class);System.out.println(user1==user2);}
2.12、实验十一:bean生命周期
①具体的生命周期过程
- 1、bean对象创建(调用无参构造器)
- 2、给bean对象设置属性
- 3、bean的后置处理器(初始化之前)
- 4、bean对象初始化(需在配置bean时指定初始化方法)
- 5、bean的后置处理器(初始化之后)
- 6、bean对象就绪可以使用
- 7、bean对象销毁(需在配置bean时指定销毁方法)
- 8、IOC容器关闭
②修改类User
publicclassUser{privateInteger id;privateString username;privateString password;privateInteger age;publicUser(){System.out.println("生命周期:1、创建对象");}publicUser(Integer id,String username,String password,Integer age){this.id = id;this.username = username;this.password = password;this.age = age;}publicIntegergetId(){return id;}publicvoidsetId(Integer id){System.out.println("生命周期:2、依赖注入");this.id = id;}publicStringgetUsername(){return username;}publicvoidsetUsername(String username){this.username = username;}publicStringgetPassword(){return password;}publicvoidsetPassword(String password){this.password = password;}publicIntegergetAge(){return age;}publicvoidsetAge(Integer age){this.age = age;}publicvoidinitMethod(){System.out.println("生命周期:3、初始化");}publicvoiddestroyMethod(){System.out.println("生命周期:5、销毁");}@OverridepublicStringtoString(){return"User{"+"id="+ id +", username='"+ username +'\''+", password='"+ password +'\''+", age="+ age +'}';}}
注意其中的
initMethod()
和
destroyMethod()
,可以通过配置bean指定为初始化和销毁的方法
③配置bean
<!-- 使用init-method属性指定初始化方法 --><!-- 使用destroy-method属性指定销毁方法 --><beanclass="org.example.bean.User"scope="prototype"init-method="initMethod"destroy-method="destroyMethod"><propertyname="id"value="1001"></property><propertyname="username"value="admin"></property><propertyname="password"value="123456"></property><propertyname="age"value="23"></property></bean>
④测试
@TestpublicvoidtestLife(){ClassPathXmlApplicationContext ac =newClassPathXmlApplicationContext("spring-lifecycle.xml");User bean = ac.getBean(User.class);System.out.println("生命周期:4、通过IOC容器获取bean并使用");
ac.close();}
⑤bean的后置处理器
bean的后置处理器会在生命周期的初始化前后添加额外的操作,需要实现
BeanPostProcessor
接口,且配置到IOC容器中,需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容器中所有bean都会执行
创建bean的后置处理器:
packageorg.example.process;importorg.springframework.beans.BeansException;importorg.springframework.beans.factory.config.BeanPostProcessor;publicclassMyBeanProcessorimplementsBeanPostProcessor{@OverridepublicObjectpostProcessBeforeInitialization(Object bean,String beanName)throwsBeansException{System.out.println("☆☆☆"+ beanName +" = "+ bean);return bean;}@OverridepublicObjectpostProcessAfterInitialization(Object bean,String beanName)throwsBeansException{System.out.println("★★★"+ beanName +" = "+ bean);return bean;}}
在IOC容器中配置后置处理器:
<!-- bean的后置处理器要放入IOC容器才能生效 --><beanid="myBeanProcessor"class="org.example.process.MyBeanProcessor"/>
2.13、实验十二:FactoryBean
①简介
FactoryBean
是Spring提供的一种整合第三方框架的常用机制。和普通的bean不同,配置一个FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是
getObject()
方法的返回值。通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都屏蔽起来,只把最简洁的使用界面展示给我们。
整合Mybatis时,Spring就是通过FactoryBean机制来帮我们创建
SqlSessionFactory
对象的。
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/packageorg.springframework.beans.factory;importorg.springframework.lang.Nullable;/**
* Interface to be implemented by objects used within a {@link BeanFactory} which
* are themselves factories for individual objects. If a bean implements this
* interface, it is used as a factory for an object to expose, not directly as a
* bean instance that will be exposed itself.
*
* <p><b>NB: A bean that implements this interface cannot be used as a normal bean.</b>
* A FactoryBean is defined in a bean style, but the object exposed for bean
* references ({@link #getObject()}) is always the object that it creates.
*
* <p>FactoryBeans can support singletons and prototypes, and can either create
* objects lazily on demand or eagerly on startup. The {@link SmartFactoryBean}
* interface allows for exposing more fine-grained behavioral metadata.
*
* <p>This interface is heavily used within the framework itself, for example for
* the AOP {@link org.springframework.aop.framework.ProxyFactoryBean} or the
* {@link org.springframework.jndi.JndiObjectFactoryBean}. It can be used for
* custom components as well; however, this is only common for infrastructure code.
*
* <p><b>{@code FactoryBean} is a programmatic contract. Implementations are not
* supposed to rely on annotation-driven injection or other reflective facilities.</b>
* {@link #getObjectType()} {@link #getObject()} invocations may arrive early in the
* bootstrap process, even ahead of any post-processor setup. If you need access to
* other beans, implement {@link BeanFactoryAware} and obtain them programmatically.
*
* <p><b>The container is only responsible for managing the lifecycle of the FactoryBean
* instance, not the lifecycle of the objects created by the FactoryBean.</b> Therefore,
* a destroy method on an exposed bean object (such as {@link java.io.Closeable#close()}
* will <i>not</i> be called automatically. Instead, a FactoryBean should implement
* {@link DisposableBean} and delegate any such close call to the underlying object.
*
* <p>Finally, FactoryBean objects participate in the containing BeanFactory's
* synchronization of bean creation. There is usually no need for internal
* synchronization other than for purposes of lazy initialization within the
* FactoryBean itself (or the like).
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 08.03.2003
* @param <T> the bean type
* @see org.springframework.beans.factory.BeanFactory
* @see org.springframework.aop.framework.ProxyFactoryBean
* @see org.springframework.jndi.JndiObjectFactoryBean
*/publicinterfaceFactoryBean<T>{/**
* The name of an attribute that can be
* {@link org.springframework.core.AttributeAccessor#setAttribute set} on a
* {@link org.springframework.beans.factory.config.BeanDefinition} so that
* factory beans can signal their object type when it can't be deduced from
* the factory bean class.
* @since 5.2
*/String OBJECT_TYPE_ATTRIBUTE ="factoryBeanObjectType";/**
* Return an instance (possibly shared or independent) of the object
* managed by this factory.
* <p>As with a {@link BeanFactory}, this allows support for both the
* Singleton and Prototype design pattern.
* <p>If this FactoryBean is not fully initialized yet at the time of
* the call (for example because it is involved in a circular reference),
* throw a corresponding {@link FactoryBeanNotInitializedException}.
* <p>As of Spring 2.0, FactoryBeans are allowed to return {@code null}
* objects. The factory will consider this as normal value to be used; it
* will not throw a FactoryBeanNotInitializedException in this case anymore.
* FactoryBean implementations are encouraged to throw
* FactoryBeanNotInitializedException themselves now, as appropriate.
* @return an instance of the bean (can be {@code null})
* @throws Exception in case of creation errors
* @see FactoryBeanNotInitializedException
*/@NullableTgetObject()throwsException;/**
* Return the type of object that this FactoryBean creates,
* or {@code null} if not known in advance.
* <p>This allows one to check for specific types of beans without
* instantiating objects, for example on autowiring.
* <p>In the case of implementations that are creating a singleton object,
* this method should try to avoid singleton creation as far as possible;
* it should rather estimate the type in advance.
* For prototypes, returning a meaningful type here is advisable too.
* <p>This method can be called <i>before</i> this FactoryBean has
* been fully initialized. It must not rely on state created during
* initialization; of course, it can still use such state if available.
* <p><b>NOTE:</b> Autowiring will simply ignore FactoryBeans that return
* {@code null} here. Therefore it is highly recommended to implement
* this method properly, using the current state of the FactoryBean.
* @return the type of object that this FactoryBean creates,
* or {@code null} if not known at the time of the call
* @see ListableBeanFactory#getBeansOfType
*/@NullableClass<?>getObjectType();/**
* Is the object managed by this factory a singleton? That is,
* will {@link #getObject()} always return the same object
* (a reference that can be cached)?
* <p><b>NOTE:</b> If a FactoryBean indicates to hold a singleton object,
* the object returned from {@code getObject()} might get cached
* by the owning BeanFactory. Hence, do not return {@code true}
* unless the FactoryBean always exposes the same reference.
* <p>The singleton status of the FactoryBean itself will generally
* be provided by the owning BeanFactory; usually, it has to be
* defined as singleton there.
* <p><b>NOTE:</b> This method returning {@code false} does not
* necessarily indicate that returned objects are independent instances.
* An implementation of the extended {@link SmartFactoryBean} interface
* may explicitly indicate independent instances through its
* {@link SmartFactoryBean#isPrototype()} method. Plain {@link FactoryBean}
* implementations which do not implement this extended interface are
* simply assumed to always return independent instances if the
* {@code isSingleton()} implementation returns {@code false}.
* <p>The default implementation returns {@code true}, since a
* {@code FactoryBean} typically manages a singleton instance.
* @return whether the exposed object is a singleton
* @see #getObject()
* @see SmartFactoryBean#isPrototype()
*/defaultbooleanisSingleton(){returntrue;}}
②创建类UserFactoryBean
packageorg.example.bean;publicclassUserFactoryBeanimplementsFactoryBean<User>{@OverridepublicUsergetObject()throwsException{returnnewUser();}@OverridepublicClass<?>getObjectType(){returnUser.class;}}
③配置bean
<beanid="user"class="org.example.bean.UserFactoryBean"></bean>
④测试
@TestpublicvoidtestUserFactoryBean(){//获取IOC容器ApplicationContext ac =newClassPathXmlApplicationContext("spring-factorybean.xml");User user =(User) ac.getBean("user");System.out.println(user);}
2.14、实验十三:基于xml自动装配
自动装配:
根据指定的策略,在IOC容器中匹配某一个bean,自动为指定的bean中所依赖的类类型或接口类型属性赋值
①场景模拟
创建类UserController
packageorg.example.autowire.controller;publicclassUserController{privateUserService userService;publicvoidsetUserService(UserService userService){this.userService = userService;}publicvoidsaveUser(){
userService.saveUser();}}
创建接口UserService
packageorg.example.autowire.service;publicinterfaceUserService{voidsaveUser();}
创建类UserServiceImpl实现接口UserService
packageorg.example.autowire.service.impl;publicclassUserServiceImplimplementsUserService{privateUserDao userDao;publicvoidsetUserDao(UserDao userDao){this.userDao = userDao;}@OverridepublicvoidsaveUser(){
userDao.saveUser();}}
创建接口UserDao
packageorg.example.autowire.dao;publicinterfaceUserDao{voidsaveUser();}
创建类UserDaoImpl实现接口UserDao
packageorg.example.autowire.dao.impl;publicclassUserDaoImplimplementsUserDao{@OverridepublicvoidsaveUser(){System.out.println("保存成功");}}
②配置bean
使用bean标签的
autowire
属性设置自动装配效果
自动装配方式:
byType
byType
:根据类型匹配IOC容器中的某个兼容类型的bean,为属性自动赋值
若在IOC中,没有任何一个兼容类型的bean能够为属性赋值,则该属性不装配,即值为默认值null
若在IOC中,有多个兼容类型的bean能够为属性赋值,则抛出异常NoUniqueBeanDefinitionException
<beanid="userController"class="org.example.autowire.controller.UserController"autowire="byType"></bean><beanid="userService"class="org.example.autowire.service.impl.UserServiceImpl"autowire="byType"></bean><beanid="userDao"class="org.example.autowire.dao.impl.UserDaoImpl"></bean>
自动装配方式:
byName
byName
:将自动装配的属性的属性名,作为bean的id在IOC容器中匹配相对应的bean进行赋值
<beanid="userController"class="org.example.autowire.controller.UserController"autowire="byName"></bean><beanid="userService"class="org.example.autowire.service.impl.UserServiceImpl"autowire="byName"></bean><beanid="userServiceImpl"class="org.example.autowire.service.impl.UserServiceImpl"autowire="byName"></bean><beanid="userDao"class="org.example.autowire.dao.impl.UserDaoImpl"></bean><beanid="userDaoImpl"class="org.example.autowire.dao.impl.UserDaoImpl"></bean>
③测试
@TestpublicvoidtestAutoWireByXML(){ApplicationContext ac =newClassPathXmlApplicationContext("autowire-xml.xml");UserController userController = ac.getBean(UserController.class);
userController.saveUser();}
3、基于注解管理Bean
从 Java 5 开始,Java 增加了对注解(Annotation)的支持,它是代码中的一种特殊标记,可以在编译、类加载和运行时被读取,执行相应的处理。开发人员可以通过注解在不改变原有代码和逻辑的情况下,在源代码中嵌入补充信息。
Spring 从 2.5 版本开始提供了对注解技术的全面支持,我们可以使用注解来实现自动装配,简化 Spring 的 XML 配置。
Spring 通过注解实现自动装配的步骤如下:
- 引入依赖
- 开启组件扫描
- 使用注解定义 Bean
- 依赖注入
3.1、搭建子模块spring6-ioc-annotation
①搭建模块
搭建方式如:spring6-ioc-xml
②引入配置文件
引入spring-ioc-xml模块日志log4j2.xml
③添加依赖
<dependencies><!--spring context依赖--><!--当你引入Spring Context依赖之后,表示将Spring的基础依赖引入了--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.3</version></dependency><!--junit5测试--><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId></dependency><!--log4j2的依赖--><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.19.0</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-slf4j2-impl</artifactId><version>2.19.0</version></dependency></dependencies>
3.2、开启组件扫描
Spring 默认不使用注解装配 Bean,因此我们需要在 Spring 的 XML 配置中,通过
<context:component-scan>
元素开启 Spring Beans的自动扫描功能。开启此功能后,Spring 会自动从扫描指定的包(
base-package
属性设置)及其子包下的所有类,如果类上使用了
@Component
注解,就将该类装配到容器中。
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"><!--开启组件扫描功能--><context:component-scanbase-package="org.example"></context:component-scan></beans>
注意:在使用
<context:component-scan>
元素开启自动扫描功能前,首先需要在 XML 配置的一级标签
<beans>
中添加 context 相关的约束。
情况一:最基本的扫描方式
<context:component-scanbase-package="org.example"></context:component-scan>
情况二:指定要排除的组件
<context:component-scanbase-package="org.example"><!-- context:exclude-filter标签:指定排除规则 --><!--
type:设置排除或包含的依据
type="annotation",根据注解排除,expression中设置要排除的注解的全类名
type="assignable",根据类型排除,expression中设置要排除的类型的全类名
--><context:exclude-filtertype="annotation"expression="org.springframework.stereotype.Controller"/><!--<context:exclude-filter type="assignable" expression="org.example.controller.UserController"/>--></context:component-scan>
情况三:仅扫描指定组件
<context:component-scanbase-package="org.example"use-default-filters="false"><!-- context:include-filter标签:指定在原有扫描规则的基础上追加的规则 --><!-- use-default-filters属性:取值false表示关闭默认扫描规则 --><!-- 此时必须设置use-default-filters="false",因为默认规则即扫描指定包下所有类 --><!--
type:设置排除或包含的依据
type="annotation",根据注解排除,expression中设置要排除的注解的全类名
type="assignable",根据类型排除,expression中设置要排除的类型的全类名
--><context:include-filtertype="annotation"expression="org.springframework.stereotype.Controller"/><!--<context:include-filter type="assignable" expression="org.example.controller.UserController"/>--></context:component-scan>
3.3、使用注解定义 Bean
Spring 提供了以下多个注解,这些注解可以直接标注在 Java 类上,将它们定义成 Spring Bean。
注解说明@Component该注解用于描述 Spring 中的 Bean,它是一个泛化的概念,仅仅表示容器中的一个组件(Bean),并且可以作用在应用的任何层次,例如 Service 层、Dao 层等。 使用时只需将该注解标注在相应类上即可。@Repository该注解用于将数据访问层(Dao 层)的类标识为 Spring 中的 Bean,其功能与 @Component 相同。@Service该注解通常作用在业务层(Service 层),用于将业务层的类标识为 Spring 中的 Bean,其功能与 @Component 相同。@Controller该注解通常作用在控制层(如SpringMVC 的 Controller),用于将控制层的类标识为 Spring 中的 Bean,其功能与 @Component 相同。
3.4、实验一:@Autowired注入
单独使用
@Autowired
注解,默认根据类型装配。【默认是byType】
查看源码:
packageorg.springframework.beans.factory.annotation;importjava.lang.annotation.Documented;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;@Target({ElementType.CONSTRUCTOR,ElementType.METHOD,ElementType.PARAMETER,ElementType.FIELD,ElementType.ANNOTATION_TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic@interfaceAutowired{booleanrequired()defaulttrue;}
源码中有两处需要注意:
- 第一处:该注解可以标注在哪里?
- 构造方法上- 方法上- 形参上- 属性上- 注解上
- 第二处:该注解有一个
required
属性,默认值是true,表示在注入的时候要求被注入的Bean必须是存在的,如果不存在则报错。如果required属性设置为false,表示注入的Bean存在或者不存在都没关系,存在的话就注入,不存在的话,也不报错。
①场景一:属性注入
创建UserDao接口
packageorg.example.dao;publicinterfaceUserDao{publicvoidprint();}
创建UserDaoImpl实现
packageorg.example.dao.impl;importorg.example.dao.UserDao;importorg.springframework.stereotype.Repository;@RepositorypublicclassUserDaoImplimplementsUserDao{@Overridepublicvoidprint(){System.out.println("Dao层执行结束");}}
创建UserService接口
packageorg.example.spring6.service;publicinterfaceUserService{publicvoidout();}
创建UserServiceImpl实现类
packageorg.example.spring6.service.impl;importorg.example.spring6.dao.UserDao;importorg.example.spring6.service.UserService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;@ServicepublicclassUserServiceImplimplementsUserService{@AutowiredprivateUserDao userDao;@Overridepublicvoidout(){
userDao.print();System.out.println("Service层执行结束");}}
创建UserController类
packageorg.exampleu.spring6.controller;importorg.example.spring6.service.UserService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;@ControllerpublicclassUserController{@AutowiredprivateUserService userService;publicvoidout(){
userService.out();System.out.println("Controller层执行结束。");}}
测试一
packageorg.example.spring6.bean;importorg.example.spring6.controller.UserController;importorg.junit.jupiter.api.Test;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;publicclassUserTest{privateLogger logger =LoggerFactory.getLogger(UserTest.class);@TestpublicvoidtestAnnotation(){ApplicationContext context =newClassPathXmlApplicationContext("Beans.xml");UserController userController = context.getBean("userController",UserController.class);
userController.out();
logger.info("执行成功");}}
以上构造方法和setter方法都没有提供,经过测试,仍然可以注入成功。
②场景二:set注入
修改UserServiceImpl类
packageorg.example.service.impl;importorg.example.dao.UserDao;importorg.example.service.UserService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;@ServicepublicclassUserServiceImplimplementsUserService{privateUserDao userDao;@AutowiredpublicvoidsetUserDao(UserDao userDao){this.userDao = userDao;}@Overridepublicvoidout(){
userDao.print();System.out.println("Service层执行结束");}}
修改UserController类
packageorg.example.controller;importorg.example.service.UserService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;@ControllerpublicclassUserController{privateUserService userService;@AutowiredpublicvoidsetUserService(UserService userService){this.userService = userService;}publicvoidout(){
userService.out();System.out.println("Controller层执行结束。");}}
测试:成功调用
③场景三:构造方法注入
修改UserServiceImpl类
packageorg.example.service.impl;importorg.example.dao.UserDao;importorg.example.service.UserService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;@ServicepublicclassUserServiceImplimplementsUserService{privateUserDao userDao;@AutowiredpublicUserServiceImpl(UserDao userDao){this.userDao = userDao;}@Overridepublicvoidout(){
userDao.print();System.out.println("Service层执行结束");}}
修改UserController类
packageorg.example.controller;importorg.example.service.UserService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;@ControllerpublicclassUserController{privateUserService userService;@AutowiredpublicUserController(UserService userService){this.userService = userService;}publicvoidout(){
userService.out();System.out.println("Controller层执行结束。");}}
测试:成功调用
注:在 Spring4.x 中增加了新的特性:如果类只提供了一个带参数的构造方法,则不需要对对其内部的属性写 @Autowired 注解,Spring 会自动为你注入属性。(请看场景五)
④场景四:形参上注入
修改UserServiceImpl类
packageorg.example.service.impl;importorg.example.spring6.dao.UserDao;importorg.example.service.UserService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;@ServicepublicclassUserServiceImplimplementsUserService{privateUserDao userDao;publicUserServiceImpl(@AutowiredUserDao userDao){this.userDao = userDao;}@Overridepublicvoidout(){
userDao.print();System.out.println("Service层执行结束");}}
修改UserController类
packageorg.example.controller;importorg.example.service.UserService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;@ControllerpublicclassUserController{privateUserService userService;publicUserController(@AutowiredUserService userService){this.userService = userService;}publicvoidout(){
userService.out();System.out.println("Controller层执行结束。");}}
测试:成功调用
⑤场景五:只有一个构造函数,无注解
修改UserServiceImpl类
packageorg.example.service.impl;importorg.example.dao.UserDao;importorg.example.service.UserService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.stereotype.Service;@ServicepublicclassUserServiceImplimplementsUserService{@AutowiredprivateUserDao userDao;publicUserServiceImpl(UserDao userDao){this.userDao = userDao;}@Overridepublicvoidout(){
userDao.print();System.out.println("Service层执行结束");}}
测试通过
当有参数的构造方法只有一个时,@Autowired注解可以省略。
说明:有多个构造方法时呢?大家可以测试(再添加一个无参构造函数),测试报错
⑥场景六:@Autowired注解和@Qualifier注解联合
添加dao层实现
packageorg.example.dao.impl;importorg.example.dao.UserDao;importorg.springframework.stereotype.Repository;@RepositorypublicclassUserDaoRedisImplimplementsUserDao{@Overridepublicvoidprint(){System.out.println("Redis Dao层执行结束");}}
测试:测试异常
错误信息中说:不能装配,UserDao这个Bean的数量等于2
怎么解决这个问题呢?当然要byName,根据名称进行装配了。
修改UserServiceImpl类
packageorg.example.service.impl;importorg.example.dao.UserDao;importorg.example.service.UserService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;@ServicepublicclassUserServiceImplimplementsUserService{@Autowired@Qualifier("userDaoImpl")// 指定bean的名字privateUserDao userDao;@Overridepublicvoidout(){
userDao.print();System.out.println("Service层执行结束");}}
总结
@Autowired
注解可以出现在:属性上、构造方法上、构造方法的参数上、setter方法上。- 当带参数的构造方法只有一个,@Autowired注解可以省略。()
- @Autowired注解默认根据类型注入。如果要根据名称注入的话,需要配合
@Qualifier
注解一起使用。
3.5、实验二:@Resource注入
@Resource
注解也可以完成属性注入。那它和@Autowired注解有什么区别?
@Resource
注解是JDK扩展包中的,也就是说属于JDK的一部分。所以该注解是标准注解,更加具有通用性。(JSR-250标准中制定的注解类型。JSR是Java规范提案。)- @Autowired注解是Spring框架自己的。
- @Resource注解默认根据名称装配byName,未指定name时,使用属性名作为name。通过name找不到的话会自动启动通过类型byType装配。
- @Autowired注解默认根据类型装配byType,如果想根据名称装配,需要配合@Qualifier注解一起用。
- @Resource注解用在属性上、setter方法上。
- @Autowired注解用在属性上、setter方法上、构造方法上、构造方法参数上。
@Resource注解属于JDK扩展包,所以不在JDK当中,需要额外引入以下依赖:【如果是JDK8的话不需要额外引入依赖。高于JDK11或低于JDK8需要引入以下依赖。】
<dependency><groupId>jakarta.annotation</groupId><artifactId>jakarta.annotation-api</artifactId><version>2.1.1</version></dependency>
源码:
packagejakarta.annotation;importjava.lang.annotation.ElementType;importjava.lang.annotation.Repeatable;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Repeatable(Resources.class)public@interfaceResource{Stringname()default"";Stringlookup()default"";Class<?>type()defaultObject.class;Resource.AuthenticationTypeauthenticationType()defaultResource.AuthenticationType.CONTAINER;booleanshareable()defaulttrue;StringmappedName()default"";Stringdescription()default"";publicstaticenumAuthenticationType{
CONTAINER,
APPLICATION;privateAuthenticationType(){}}}
①场景一:根据name注入
修改UserDaoImpl类
packageorg.example.dao.impl;importorg.example.dao.UserDao;importorg.springframework.stereotype.Repository;@Repository("myUserDao")publicclassUserDaoImplimplementsUserDao{@Overridepublicvoidprint(){System.out.println("Dao层执行结束");}}
修改UserServiceImpl类
packageorg.example.service.impl;importorg.example.dao.UserDao;importorg.example.service.UserService;importjakarta.annotation.Resource;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.stereotype.Service;@ServicepublicclassUserServiceImplimplementsUserService{@Resource(name ="myUserDao")privateUserDao myUserDao;@Overridepublicvoidout(){
myUserDao.print();System.out.println("Service层执行结束");}}
测试通过
②场景二:name未知注入
修改UserDaoImpl类
packageorg.example.dao.impl;importorg.example.dao.UserDao;importorg.springframework.stereotype.Repository;@Repository("myUserDao")publicclassUserDaoImplimplementsUserDao{@Overridepublicvoidprint(){System.out.println("Dao层执行结束");}}
修改UserServiceImpl类
packageorg.example.service.impl;importorg.example.dao.UserDao;importorg.example.service.UserService;importjakarta.annotation.Resource;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.stereotype.Service;@ServicepublicclassUserServiceImplimplementsUserService{@ResourceprivateUserDao myUserDao;@Overridepublicvoidout(){
myUserDao.print();System.out.println("Service层执行结束");}}
测试通过
当
@Resource
注解使用时没有指定name的时候,还是根据name进行查找,这个name是 属性名 。
③场景三 其他情况
修改UserServiceImpl类,userDao1属性名不存在
packageorg.example.service.impl;importorg.example.dao.UserDao;importorg.example.service.UserService;importjakarta.annotation.Resource;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.stereotype.Service;@ServicepublicclassUserServiceImplimplementsUserService{@ResourceprivateUserDao userDao1;@Overridepublicvoidout(){
userDao1.print();System.out.println("Service层执行结束");}}
测试异常
根据异常信息得知:显然当通过name找不到的时候,自然会启动byType进行注入,以上的错误是因为UserDao接口下有两个实现类导致的。所以根据类型注入就会报错。
@Resource的set注入可以自行测试
总结:
@Resource注解:默认byName注入,没有指定name时把属性名当做name,根据name找不到时,才会byType注入。byType注入时,某种类型的Bean只能有一个
3.6、Spring全注解开发
全注解开发就是不再使用spring配置文件了,写一个配置类来代替配置文件。
packageorg.example.config;importorg.springframework.context.annotation.ComponentScan;importorg.springframework.context.annotation.Configuration;@Configuration//@ComponentScan({"org.example.controller", "org.example.service","org.example.dao"})@ComponentScan("org.example")publicclassSpring6Config{}
测试类
@TestpublicvoidtestAllAnnotation(){ApplicationContext context =newAnnotationConfigApplicationContext(Spring6Config.class);UserController userController = context.getBean("userController",UserController.class);
userController.out();
logger.info("执行成功");}
版权归原作者 鱼找水需要时间 所有, 如有侵权,请联系我们删除。