spring 注解方式配置Bean

概要:




再classpath中扫描组件

  • 组件扫描(component scanning):Spring可以从classpath下自己主动扫描。侦測和实例化具有特定注解的组件
  • 特定组件包含:
    • @Component:基本注解。标示了一个受Spring管理的组件(能够混用。spring还无法识别详细是哪一层)
    • @Respository:建议标识持久层组件(能够混用。spring还无法识别详细是哪一层)
    • @Service:建议标识服务层(业务层)组件(能够混用,spring还无法识别详细是哪一层)
    • @Controller:建议标识表现层组件(能够混用,spring还无法识别详细是哪一层)
  • 对于扫描到的组件,Spring有默认的命名策略:使用非限定类名,第一个字母小写(UserServiceImpl-》userServiceImpl),也能够再注解中通过value属性值标识组件的名称(通常能够将UserServiceImpl —》userService,能够将Impl拿掉,这是一个习惯)

在classpath中扫描组件
  • 当在组件类中使用了特定的注解之后,还须要在Spring的配置文件里声明<context:component-scan>:
    • base-package属性指定一个须要扫描的基类包,Spring容器将会扫描整个基类包里及其子包中的全部类
    • 当须要扫描多个包时,能够使用逗号分隔
    • 假设仅希望扫描特定的类而非基包下的全部类,可使用resource-pattern属性过滤特定的类。实例: 
    • <context:include-filter>子节点表示要包括的目标类
    • <context:exclude-filter>子节点表示要排除在外的目标类
    • <context:component-scan>下能够拥有若干个<context:include-filter>和<context:exclude-filter>子节点
    • <context:include-filter>和<context:exclude-filter>子节点支持多种类型的过滤表达式: 

组件装配
  • <context:component-sacn>元素还会自己主动注冊AutowireAnnotationBeanPostProcessor实例。该实例能够自己主动装配具有@Autowired和@Resource、@Inject注解的属性

使用@Autowired自己主动装配Bean
  • @Autowired注解自己主动装配具有兼容类型的单个Bean属性
    • 能够放在构造器或普通字段(即使是非public)或一切具有參数的方法都能够应用@Authwired注解
    • 默认情况下,全部使用@Autowired注解的属性都须要被设置。当Spring找不到匹配的Bean装配属性时,会抛出异常。若某一属性同意不被设置,能够设置@Authwired注解的required属性为false
    • 默认情况下,当IOC容器里存在多个类型兼容的Bean时(@Autowired先是依照类型匹配Bean。假设存在多个类型同样的Bean,此时IOC容器会去寻找与属性名同样名字的Bean),通过类型的自己主动装配将无法工作,此时能够在@Qualifier注解里Bean属性的名称。Spring同意对方法的方法的输入參数标注@Qualifier以指定注入Bean的名称
    • @Authwired注解也能够应用在数组类型的属性上。此时Spring将会把全部匹配的Bean进行自己主动装配
    • @Authwired注解也能够应用在集合属性上。此时Spring读取该集合的类型信息。然后自己主动装配全部与之兼容的Bean
    • @Authwired注解用在java.util.Map上时,若该Map的键值为String,那么Spring将会自己主动装配与之Map值类型兼容的Bean,此时Bean的名称作为键值

 使用@Resource或@Inject自己主动装配Bean
  • Spring还支持@Resource和@Inject注解。这两个注解和@Autowired注解的功能类似
  • @Resource注解要求提供一个Bean名称的属性,若该属性为空,则自己主动採用标注处的变量或方法名作为Bean的名称
  • @Inject和@Autowired注解一样也是依照类型匹配注入的Bean,但没有required属性
  • 建议使用@Autowired注解


实例代码具体解释:
代码结构

注意:使用注解还须要导入spring-aop-4.0.5.RELEAE.jar这个包


TestObject.java
package com.coslay.beans.annotation;import org.springframework.stereotype.Component;public class TestObject {}


UserController.java
package com.coslay.beans.annotation.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;import com.coslay.beans.annotation.service.UserService;@Controller
public class UserController {@Autowiredprivate UserService userService;public void execute(){System.out.println("UserController execute...");userService.add();}
}



UserService.java
package com.coslay.beans.annotation.service;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;import com.coslay.beans.annotation.reporsitory.UserRepository;@Service
public class UserService {private UserRepository userRepository;//假设有多个类型匹配时。则会去匹配与这个属性名字同样的Bean的名字//@Repository("userRepository")//public class UserRepositoryImpl implements UserRepository{//由于名字同样所以匹配成功//能够将@Autowired放在字段或者方法上//假设没有指定名字//另一种方法是使用@Qualifier("userRepositoryImpl")//用来指定哪一个指定名字的Bean//能够将该标签放在字段,设置方法或者设置方法的传入參数前面@Autowired@Qualifier("userRepositoryImpl")public void setUserRepository(UserRepository userRepository){this.userRepository = userRepository;}//	@Autowired
//	public void setUserRepository(@Qualifier("userRepositoryImpl") UserRepository userRepository){
//		this.userRepository = userRepository;
//	}public void add(){System.out.println("UserService add...");userRepository.sava();}
}


UserRepository.java
package com.coslay.beans.annotation.reporsitory;public interface UserRepository {void sava();}



UserRepositoryImpl.java
package com.coslay.beans.annotation.reporsitory;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;import com.coslay.beans.annotation.TestObject;@Repository("userRepository")
public class UserRepositoryImpl implements UserRepository{@Autowired(required=false)private TestObject testObject;@Overridepublic void sava() {System.out.println("UserRepository Save...");System.out.println(testObject);}}


UserJdbcRepository.java
package com.coslay.beans.annotation.reporsitory;import org.springframework.stereotype.Repository;@Repository
public class UserJdbcRepository implements UserRepository {@Overridepublic void sava() {System.out.println("UserJdbcRepository sava...");}}



Main.java
package com.coslay.beans.annotation;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.coslay.beans.annotation.controller.UserController;
import com.coslay.beans.annotation.reporsitory.UserRepository;
import com.coslay.beans.annotation.service.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 userController = (UserController) ctx.getBean("userController");System.out.println(userController);userController.execute();//		
//		UserService userService = (UserService) ctx.getBean("userService");
//		System.out.println(userService);
//		
//		UserRepository userRepository = (UserRepository) ctx.getBean("userRepository");
//		System.out.println(userRepository);}
}


beans-annotation.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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 指定Spring IOC 容器扫描的包 --> <!-- 能够通过resource-pattern指定扫描的资源 --> <!-- <context:component-scan base-package="com.coslay.beans.annotation" resource-pattern="reporsitory/*.class"> </context:component-scan> --> <!-- context:exclude-filter 子节点指定排除哪些指定表达式的组件 context:include-filter 子节点指定包括哪些表达式的组件,该子节点须要use-default-filters="false"配合使用(假设use-default-filters="ture"则使用系统默认扫描全部带有@Component@Controller@Service@Repository的组件) --> <context:component-scan base-package="com.coslay.beans.annotation"> <!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/> --> <!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/> --> <!-- <context:exclude-filter type="assignable" expression="com.coslay.beans.annotation.reporsitory.UserRepository"/> --> <!-- <context:include-filter type="assignable" expression="com.coslay.beans.annotation.reporsitory.UserRepository"/> --> </context:component-scan> </beans>



转载于:https://www.cnblogs.com/liguangsunls/p/7349604.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/391701.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

主成分分析 独立成分分析_主成分分析概述

主成分分析 独立成分分析by Moshe Binieli由Moshe Binieli 主成分分析概述 (An overview of Principal Component Analysis) This article will explain you what Principal Component Analysis (PCA) is, why we need it and how we use it. I will try to make it as simple…

扩展方法略好于帮助方法

如果针对一个类型实例的代码片段经常被用到&#xff0c;我们可能会想到把之封装成帮助方法。如下是一段针对DateTime类型实例的一段代码&#xff1a;class Program{static void Main(string[] args){DateTime d new DateTime(2001,5,18);switch (d.DayOfWeek){case DayOfWeek.…

零元学Expression Blend 4 - Chapter 25 以Text相关功能就能简单做出具有设计感的登入画面...

原文:零元学Expression Blend 4 - Chapter 25 以Text相关功能就能简单做出具有设计感的登入画面本章将交大家如何运用Blend 4 内的Text相关功能做出有设计感的登入画面 让你五分钟就能快速做出一个登入画面 ? 本章将教大家如何运用Blend 4 内的Text相关功能做出有设计感的登入…

leetcode 395. 至少有 K 个重复字符的最长子串(滑动窗口)

给你一个字符串 s 和一个整数 k &#xff0c;请你找出 s 中的最长子串&#xff0c; 要求该子串中的每一字符出现次数都不少于 k 。返回这一子串的长度。 示例 1&#xff1a; 输入&#xff1a;s “aaabb”, k 3 输出&#xff1a;3 解释&#xff1a;最长子串为 “aaa” &…

冠状病毒时代的负责任数据可视化

First, a little bit about me: I’m a data science grad student. I have been writing for Medium for a little while now. I’m a scorpio. I like long walks on beaches. And writing for Medium made me realize the importance of taking personal responsibility ove…

集合_java集合框架

转载自http://blog.csdn.net/zsw101259/article/details/7570033 Java集合框架图 简化图&#xff1a; Java平台提供了一个全新的集合框架。“集合框架”主要由一组用来操作对象的接口组成。不同接口描述一组不同数据类型。 1、Java 2集合框架图 ①集合接口&#xff1a;6个…

显示随机键盘

显示随机键盘 1 <!DOCTYPE html>2 <html lang"zh-cn">3 <head>4 <meta charset"utf-8">5 <title>7-77 课堂演示</title>6 <link rel"stylesheet" type"text/css" href"style…

数据特征分析-统计分析

一、统计分析 统计分析是对定量数据进行统计描述&#xff0c;常从集中趋势和离中趋势两个方面分析。 集中趋势&#xff1a;指一组数据向某一中心靠拢的倾向&#xff0c;核心在于寻找数据的代表值或中心值-统计平均数&#xff08;算数平均数和位置平均数&#xff09; 算术平均数…

心学 禅宗_禅宗宣言,用于有效的代码审查

心学 禅宗by Jean-Charles Fabre通过让查尔斯法布尔(Jean-Charles Fabre) 禅宗宣言&#xff0c;用于有效的代码审查 (A zen manifesto for effective code reviews) When you are coding, interruptions really suck.当您编码时&#xff0c;中断确实很糟糕。 You are in the …

leetcode 896. 单调数列

如果数组是单调递增或单调递减的&#xff0c;那么它是单调的。 如果对于所有 i < j&#xff0c;A[i] < A[j]&#xff0c;那么数组 A 是单调递增的。 如果对于所有 i < j&#xff0c;A[i]> A[j]&#xff0c;那么数组 A 是单调递减的。 当给定的数组 A 是单调数组…

数据eda_银行数据EDA:逐步

数据edaThis banking data was retrieved from Kaggle and there will be a breakdown on how the dataset will be handled from EDA (Exploratory Data Analysis) to Machine Learning algorithms.该银行数据是从Kaggle检索的&#xff0c;将详细介绍如何将数据集从EDA(探索性…

结构型模式之组合

重新看组合/合成&#xff08;Composite&#xff09;模式&#xff0c;发现它并不像自己想象的那么简单&#xff0c;单纯从整体和部分关系的角度去理解还是不够的&#xff0c;并且还有一些通俗的模式讲解类的书&#xff0c;由于其举的例子太过“通俗”&#xff0c;以致让人理解产…

计算机网络原理笔记-三次握手

三次握手协议指的是在发送数据的准备阶段&#xff0c;服务器端和客户端之间需要进行三次交互&#xff1a; 第一次握手&#xff1a;客户端发送syn包(synj)到服务器&#xff0c;并进入SYN_SEND状态&#xff0c;等待服务器确认&#xff1b; 第二次握手&#xff1a;服务器收到syn包…

VB2010 的隐式续行(Implicit Line Continuation)

VB2010 的隐式续行&#xff08;Implicit Line Continuation&#xff09;许多情况下,您可以让 VB 后一行继续前一行的语句&#xff0c;而不必使用下划线&#xff08;_&#xff09;。下面列举出隐式续行语法的使用情形。1、逗号“&#xff0c;”之后PublicFunctionGetUsername(By…

flutter bloc_如何在Flutter中使用Streams,BLoC和SQLite

flutter blocRecently, I’ve been working with streams and BLoCs in Flutter to retrieve and display data from an SQLite database. Admittedly, it took me a very long time to make sense of them. With that said, I’d like to go over all this in hopes you’ll w…

leetcode 303. 区域和检索 - 数组不可变

给定一个整数数组 nums&#xff0c;求出数组从索引 i 到 j&#xff08;i ≤ j&#xff09;范围内元素的总和&#xff0c;包含 i、j 两点。 实现 NumArray 类&#xff1a; NumArray(int[] nums) 使用数组 nums 初始化对象 int sumRange(int i, int j) 返回数组 nums 从索引 i …

Bigmart数据集销售预测

Note: This post is heavy on code, but yes well documented.注意&#xff1a;这篇文章讲的是代码&#xff0c;但确实有据可查。 问题描述 (The Problem Description) The data scientists at BigMart have collected 2013 sales data for 1559 products across 10 stores in…

Android控制ScrollView滑动速度

翻阅查找ScrollView的文档并搜索了一下没有发现直接设置的属性和方法&#xff0c;这里通过继承来达到这一目的。 /*** 快/慢滑动ScrollView * author农民伯伯 * */public class SlowScrollView extends ScrollView {public SlowScrollView(Context context, Att…

数据特征分析-帕累托分析

帕累托分析(贡献度分析)&#xff1a;即二八定律 目的&#xff1a;通过二八原则寻找属于20%的关键决定性因素。 随机生成数据 df pd.DataFrame(np.random.randn(10)*10003000,index list(ABCDEFGHIJ),columns [销量]) #避免出现负数 df.sort_values(销量,ascending False,i…

leetcode 304. 二维区域和检索 - 矩阵不可变(前缀和)

给定一个二维矩阵&#xff0c;计算其子矩形范围内元素的总和&#xff0c;该子矩阵的左上角为 (row1, col1) &#xff0c;右下角为 (row2, col2) 。 上图子矩阵左上角 (row1, col1) (2, 1) &#xff0c;右下角(row2, col2) (4, 3)&#xff0c;该子矩形内元素的总和为 8。 示…