[Spring] 基于注解来配置Bean

2024-05-09 05:08
文章标签 spring bean 注解 配置 java

本文主要是介绍[Spring] 基于注解来配置Bean,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Bean的配置方式

  • 基于XML文件的方式
  • 基于注解的方式(基于注解配置Bean,基于注解来装配Bean的属性)

在classpath中扫描组件

  • 组件扫描:Spring能够从classpath下自动扫描、侦测和实例化具有特定注解的组件

  • 特定组件包括:

    • @component:基本注解,标识了一个受Spring管理的组件
    • @Respositoy:标识持久层组件
    • @Service:标识服务层组件
    • @Controller:标识表现层组件
  • 对于扫描到的组件,Spring有默认的命名规则,使用非限定类名,第一个字母小写,也可以在注解中通过value属性标识组件的名称

  • 当在组件类中使用了特定的注解后,还需要在Spring的配置文件中声明<context:component-scan>

    • TestObject.java
    package com.glemontree.spring.annotation;import org.springframework.stereotype.Component;@Component
    public class TestObject {}
    • UserController.java
    package com.glemontree.spring.annotation.controller;import org.springframework.stereotype.Controller;@Controller
    public class UserController {public void execute() {System.out.println("UserController execute...");}
    }
    • UserRepository.java UserRepositoryImpl.java
    package com.glemontree.spring.annotation.repository;public interface UserRepository {void save();
    }
    package com.glemontree.spring.annotation.repository;import org.springframework.stereotype.Repository;@Repository("userRepository")
    public class UserRepositoryImpl implements UserRepository {public void save() {// TODO Auto-generated method stubSystem.out.println("UserRepository Save...");}}
    • UserService.java
    package com.glemontree.spring.annotation.sevice;import org.springframework.stereotype.Service;@Service
    public class UserService {public void add() {System.out.println("UserService add...");}
    }
    • 配置文件:
    <?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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><!--扫描com.glemontree.spring.annotation包及其子包--><context:component-scan base-package="com.glemontree.spring.annotation"></context:component-scan>
    </beans>
    • 测试方法
    package com.glemontree.spring.annotation;import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;import com.glemontree.spring.annotation.controller.UserController;
    import com.glemontree.spring.annotation.repository.UserRepository;
    import com.glemontree.spring.annotation.sevice.UserService;public class Main {public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annotation.xml");TestObject to = (TestObject) ctx.getBean("testObject");System.out.println(to);UserController uc = (UserController) ctx.getBean("userController");System.out.println(uc);UserService us = (UserService) ctx.getBean("userService");System.out.println(us);UserRepository ur = (UserRepository) ctx.getBean("userRepository");System.out.println(ur);}
    }
    • 解析:

    • base-package:指定一个需要扫描的基类包,Spring将会扫描这个基类包里极其子包里的所有类

    • 当需要扫描多个包时,可以使用逗号分隔

    • 如果仅希望扫描特定的类而非基包下的所有类,可使用resource-pattern属性过滤特定的类:

      <!--可以通过resource-pattern指定扫描的资源-->
      <context:component-scan
                            base-package="com.glemontree.spring.beans"resource-pattern:"autowire/*.class"/>
    • <context:include-filter>子结点表示包含哪些指定表达式的组件,该子结点需要use-default-filter配合使用,即设置<context:component-scan>的use-default-filter属性为false;

      <?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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
      <context:component-scan base-package="com.glemontree.spring.annotation"use-default-filters="false"><context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
      </context:component-scan>
      </beans>
    • <context:exclude-filter>子结点表示排除哪些指定表达式的组件;

      <?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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
      <context:component-scan base-package="com.glemontree.spring.annotation"><!--不包含标注了@Repository的类--><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
      </context:component-scan>
      </beans>
    • <context:component-scan>下可以包含多个<context:include-filter><context:exclude-filter>子结点

    • <context:include-filter><context:exclude-filter>子结点支持多种类型的过滤表达式,常用的有:

      • annotation:所有标注了xxxAnnotation的类
      <?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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><context:component-scan base-package="com.glemontree.spring.annotation"><!--不包含标注了@Repository的类--><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/></context:component-scan>
      </beans>
      • assinable:所有继承或扩展xxxService的类
      <?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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><!-- <context:component-scan base-package="com.glemontree.spring.annotation"use-default-filters="false"><context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/></context:component-scan> --><context:component-scan base-package="com.glemontree.spring.annotation"use-default-filters="true"><!--排除所有UserRepository和继承自UserRepository的类--><context:exclude-filter type="assignable" expression="com.glemontree.spring.annotation.repository.UserRepository"/></context:component-scan>
      </beans>
      <?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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><!-- <context:component-scan base-package="com.glemontree.spring.annotation"use-default-filters="false"><context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/></context:component-scan> --><context:component-scan base-package="com.glemontree.spring.annotation"use-default-filters="false"><context:include-filter type="assignable" expression="com.glemontree.spring.annotation.repository.UserRepository"/></context:component-scan>
      </beans>

组件装配

<context:component-scan>元素还会自动注册AutowiredAnnotationBeanPostProcessor实例,该实例可以自动装配具有@Autowired和@Resource、@Inject注解的属性。

  • Autowired:可以自动装配具有兼容类型的单个Bean属性

    • 构造器、普通字段(即使是非public)以及一切具有参数的方法都可以应用@Autowired注解

    • 默认情况下,所有使用@Autowired注解的属性都要被设置,当Spring找不到匹配的Bean装配属性时,会抛出异常,若某一属性允许不被设置,可以设置@Autowired注解的required属性为false

    • 默认情况下,当IOC容器里存在多个类型兼容Bean时,通过类型的自动装配将无法工作,此时可以在@Qualifier注解里提供Bean的名称,Spring允许对方法的入参标注@Qualifier以指定注入Bean的名称:

    package com.glemontree.spring.annotation.sevice;import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Service;import com.glemontree.spring.annotation.repository.UserRepository;@Service
    public class UserService {private UserRepository userRepository;@Autowired@Qualifier("userRepositoryImpl") // 通过@Qualifier指定Bean的名称,注意是bean的名称而不是类的名称public void setUserRepository(UserRepository userRepository) {this.userRepository = userRepository;}public void add() {System.out.println("UserService add...");userRepository.save();}
    }

    另外一种写法如下:

    package com.glemontree.spring.annotation.sevice;import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Service;import com.glemontree.spring.annotation.repository.UserRepository;@Service
    public class UserService {private UserRepository userRepository;// 将@Qualifier写在入参的前面@Autowiredpublic void setUserRepository(@Qualifier("userRepositoryImpl")UserRepository userRepository) {this.userRepository = userRepository;}public void add() {System.out.println("UserService add...");userRepository.save();}
    }

泛型依赖注入

  • BaseRepository.java

    package com.glemontree.spring.generic.di;public class BaseRepository<T> {}
  • BaseService.java

    package com.glemontree.spring.generic.di;import org.springframework.beans.factory.annotation.Autowired;public class BaseService<T> {// BaseService依赖于BaseRepository,通过@Autowired建立关系
    @Autowired
    protected BaseRepository<T> repository;
    public void add() {System.out.println("add...");System.out.println(repository);
    }
    }
  • User.java

    package com.glemontree.spring.generic.di;public class User {}
  • UserRepositpry.java

    package com.glemontree.spring.generic.di;import org.springframework.stereotype.Repository;// 通过@Repository注解注册bean
    @Repository
    public class UserRepository extends BaseRepository<User>{}
  • UserService.java

    package com.glemontree.spring.generic.di;import org.springframework.stereotype.Service;// 通过@Service注解注册bean
    @Service
    public class UserService extends BaseService<User>{}
  • beans-generic-di.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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">// 通过下面这段话UserRepository和UserService两个bean会被注册
    <context:component-scan base-package="com.glemontree.spring.generic.di"></context:component-scan>
    </beans>

虽然UserService和UserRepository之间并没有建立直接的联系,但是两个泛型类BaseService<T>BaseRepository<T>之间通过@Autowired建立了联系,因此它们的两个子类UserService和UserRepository也建立了联系。

这篇关于[Spring] 基于注解来配置Bean的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/972471

相关文章

Java的foreach语句

foreach语句是java5的新特征之一,在遍历数组、集合方面,foreach为开发人员提供了极大的方便。 foreach语句是for语句的特殊简化版本,但是foreach语句并不能完全取代for语句,然而,任何的foreach语句都可以改写为for语句版本。 foreach并不是一个关键字,习惯上将这种特殊的for语句格式称之为“foreach”语句。从英文字面意思理解fo

关于Java的数组的使用

关于一维数组的使用 代码示例一如下: package com;public class test_array {public static void main(String[] args){//1.如何定义 一个 数组//1.1数组的声明String[] names;int[] scores;//1.2数组的初始化://1.2.1静态初始化:初始化数组与数组元素赋值同时进行nam

关于Java的URL编程

前言: 1> URL(Uniform Resource Locator):统一资源定位符,它表示 Internet 上某一资源的地址。 通过 URL 我们可以访问 Internet 上的各种网络资源,比如最常见的 www,ftp 站点。 浏览器通过解析给定的 URL 可以在网络上查找相应的文件或其他资源。  2> URL的基本结构由5部分组成: <传输协议>://<主机名>:<端口号

Java的clone()方法使用详解

前言: 我们知道,在java的object类中,有这么一个方法clone(),这个方法有什么用呢?怎样才能正确地使用这个方法呢? 下面一一来进行阐述一下 clone()方法详解: 1>clone()方法的作用 顾名思义,clone()方法的作用就是克隆的意思,引入这个方法,这样就便于我们构建属于自己的一些本地对象副本。 这样我们就不用担心因为副本对象的引用而使原生的对象发生改变。

SpringMVC+Hibernate +MySql+ EasyUI实现CRUD

SpringMVC+Hibernate +MySql+ EasyUI实现CRUD 原文地址 http://my.oschina.net/xshuai/blog/345117

企业支付宝账号开发接口教程--JAVA-UTF-8(实际操作完善中...SpringMVC+JSP)

关于即时到账的开发。审核通过。简单测试如下。 希望看的可以收藏或者赞一下哦。 1.拥有自己的支付宝企业账号。去产品商店选择适合自己的方案。并签约合同。 2.选择合适的商家收款产品并去签约。填写相应的信息 3.在商家服务会有PID和KEY是关键的东西。 4.选择自己签约的产品类型,下载对应的接口api与测试代码 即时到账收款 --alipaydirect 网银支付 -

微信OAuth授权获取用户OpenId-JAVA(个人经验)

个人微信小程序 可扫码体验 本文更新有可能先在开源中国。地址为:https://my.oschina.net/xshuai/blog/293458 https://open.weixin.qq.com/ 这个是授权登陆自己网站的和我的这个是有区别的。 带评论昵称  才同意加QQ ‍鉴于老是有人问我。就更新一下了。 更新时间 2016年10月18日 修改了测试号权限不足导致授权获取信息抛

Discuz! Ucenter API for JAVA

my.oschina.net/xshuai/blog/280242原文地址  Discuz! Ucenter API for JAVA   使用自己的项目于discuz联合登陆注册。 源码和jar文件都在http://code.google.com/p/discuz-ucenter-api-for-java/  有。 我只测试了非中文的注册。中文注册可以去http://code.goog

有懂discuz的吗?我需要在我自己的系统注册一个账号的时候,也把当前注册的账号放在discuz的用户里面。应该怎么做呀。需要discuz和java的接口吗?需要更改哪些东西。

discuz-ucenter_api_for_java 有懂discuz的吗?我需要在我自己的系统注册一个账号的时候,也把当前注册的账号放在discuz的用户里面。应该怎么做呀。需要discuz和java的接口吗?需要更改哪些东西。 所有的代码 1.UC.java package com.fivestars.interfaces.bbs.api;import java.io.IO

2014年5月3日整理java笔试题+答案和自己的代码

一.选择题(每题1分) 1. jsp 有几个内置对象?( )(单选) A 5个 B 6个 C 9个 D 8个 2. 在JAVA中,如何跳出当前的多重嵌套循环?( ) (多选) A break B return C forward Dfinally 3. 四种会话跟踪技术,哪个范围最大?( ) (单选) A page B request C session Dapplication 4. java中