首页 文章 精选 留言 我的

精选列表

搜索[MLA 技术],共10000篇文章
优秀的个人博客,低调大师

SpringFramework核心技术三:Spring时间处理和类型转换

使用 在(1)中,我们学习了蛮多的基本概念,在(2)中咱们看一下如何使用的问题。 一、以编程方式使用ConversionService 要以编程方式使用ConversionService实例,只需为其他bean注入一个引用即可: @Service public class MyService { @Autowired public MyService(ConversionService conversionService) { this.conversionService = conversionService; } public void doIt() { this.conversionService.convert(...) } } 对于大多数用例,可以使用convert指定targetType的方法,但它不适用于更复杂的类型,如参数化元素的集合。如果你想转换List的Integer到List的String程序,例如,你需要提供的源和目标类型的正式定义。 幸运的是,TypeDescriptor提供了各种选项来简单明了: DefaultConversionService cs = new DefaultConversionService(); List<Integer> input = .... cs.convert(input, TypeDescriptor.forObject(input), // List<Integer> type descriptor TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(String.class))); 请注意,DefaultConversionService自动注册转换器适用于大多数环境。这包括收集器,标转换器,也基本Object到String转换器。相同的转换器可以ConverterRegistry使用该类 上的静态 addDefaultConverters方法进行注册DefaultConversionService。 值类型转换器将被重新用于数组和集合,所以没有必要创建一个特定的转换器从转换Collection的S到 Collection的T,假设标准收集处理是适当的。 二、Spring字段格式 正如前一节所讨论的,core.convert是一种通用型转换系统。它提供统一的ConversionService API以及用于实现从一种类型到另一种类型的转换逻辑的强类型转换器SPI。Spring容器使用这个系统绑定bean属性值。另外,Spring表达式语言(SpEL)和DataBinder都使用这个系统来绑定字段值。例如,当使用SpEL需要强迫一个Short到一个Long完成的expression.setValue(Object bean, Object value)尝试,core.convert系统执行强制。 现在考虑典型客户端环境(如Web或桌面应用程序)的类型转换要求。在这样的环境中,您通常从String转换 为支持客户端回发过程,并返回String以支持视图呈现过程。另外,您经常需要本地化字符串值。更一般的core.convert Converter SPI没有直接解决这种格式化要求。为了直接解决它们,Spring 3引入了一个方便的Formatter SPI,为客户端环境提供了PropertyEditor的一个简单而强大的替代方案。 通常,在需要实现通用类型转换逻辑时使用Converter SPI; 例如,用于在java.util.Date和java.lang.Long之间进行转换。在客户端环境(如Web应用程序)中工作时需要使用Formatter SPI,并且需要解析和打印本地化的字段值。ConversionService为两个SPI提供统一的类型转换API。 1.格式化器SPI 格式化器SPI实现字段格式化逻辑很简单并且强类型化: package org.springframework.format; public interface Formatter<T> extends Printer<T>, Parser<T> { } Formatter从打印机和解析器构建块接口扩展而来: public interface Printer<T> { String print(T fieldValue, Locale locale); } import java.text.ParseException; public interface Parser<T> { T parse(String clientValue, Locale locale) throws ParseException; } 要创建自己的格式化程序,只需实现上面的格式化接口即可。例如,将T指定为要格式化的对象的类型 java.util.Date。实施print()操作以打印T的实例以在客户端区域设置中显示。实现parse()操作以从客户机语言环境返回的格式化表示中解析T的实例。如果解析尝试失败,则格式化程序应该抛出ParseException或IllegalArgumentException。注意确保您的Formatter实现是线程安全的。 format为方便起见,在子包中提供了几个格式化器实现。该number包提供了一个NumberFormatter,CurrencyFormatter并 使用a PercentFormatter来格式化java.lang.Number对象java.text.NumberFormat。该datetime包提供了一个用a DateFormatter来格式化java.util.Date对象java.text.DateFormat。该datetime.joda软件包提供基于Joda-Time库的综合日期时间格式化支持。 考虑DateFormatter作为一个示例Formatter实现: package org.springframework.format.datetime; public final class DateFormatter implements Formatter<Date> { private String pattern; public DateFormatter(String pattern) { this.pattern = pattern; } public String print(Date date, Locale locale) { if (date == null) { return ""; } return getDateFormat(locale).format(date); } public Date parse(String formatted, Locale locale) throws ParseException { if (formatted.length() == 0) { return null; } return getDateFormat(locale).parse(formatted); } protected DateFormat getDateFormat(Locale locale) { DateFormat dateFormat = new SimpleDateFormat(this.pattern, locale); dateFormat.setLenient(false); return dateFormat; } } 2.注释驱动的格式 您将会看到,字段格式可以通过字段类型或注释进行配置。要将注释绑定到格式化程序,请实现AnnotationFormatterFactory: package org.springframework.format; public interface AnnotationFormatterFactory<A extends Annotation> { Set<Class<?>> getFieldTypes(); Printer<?> getPrinter(A annotation, Class<?> fieldType); Parser<?> getParser(A annotation, Class<?> fieldType); } 例如,参数化A是您希望将格式逻辑与之关联的字段批注类型org.springframework.format.annotation.DateTimeFormat。已经 getFieldTypes()返回类型字段中的注释,可以使用上。已经 getPrinter()返回打印机打印的注释字段的值。已经 getParser()返回解析器解析一个clientValue一个注释字段。 下面的示例AnnotationFormatterFactory实现将@NumberFormat注释绑定到格式化程序。此注释允许指定数字样式或模式: public final class NumberFormatAnnotationFormatterFactory implements AnnotationFormatterFactory<NumberFormat> { public Set<Class<?>> getFieldTypes() { return new HashSet<Class<?>>(asList(new Class<?>[] { Short.class, Integer.class, Long.class, Float.class, Double.class, BigDecimal.class, BigInteger.class })); } public Printer<Number> getPrinter(NumberFormat annotation, Class<?> fieldType) { return configureFormatterFrom(annotation, fieldType); } public Parser<Number> getParser(NumberFormat annotation, Class<?> fieldType) { return configureFormatterFrom(annotation, fieldType); } private Formatter<Number> configureFormatterFrom(NumberFormat annotation, Class<?> fieldType) { if (!annotation.pattern().isEmpty()) { return new NumberFormatter(annotation.pattern()); } else { Style style = annotation.style(); if (style == Style.PERCENT) { return new PercentFormatter(); } else if (style == Style.CURRENCY) { return new CurrencyFormatter(); } else { return new NumberFormatter(); } } } } 要触发格式化,只需使用@NumberFormat注释字段即可: public class MyModel { @NumberFormat(style=Style.CURRENCY) private BigDecimal decimal; } 格式注释API org.springframework.format.annotation 包中存在可移植的格式注释API 。使用@NumberFormat格式化java.lang.Number字段。使用@DateTimeFormat格式化java.util.Date,java.util.Calendar,java.util.Long或Joda-Time字段。 以下示例使用@DateTimeFormat将java.util.Date格式化为ISO日期(yyyy-MM-dd): public class MyModel { @DateTimeFormat(iso=ISO.DATE) private Date date; } 3.FormatterRegistry SPI FormatterRegistry是用于注册格式化程序和转换程序的SPI。 FormattingConversionService是适用于大多数环境的FormatterRegistry的实现。这个实现可以通过编程或声明方式配置为Spring bean FormattingConversionServiceFactoryBean。因为这个实现也实现了ConversionService,所以它可以直接配置用于Spring的DataBinder和Spring表达式语言(SpEL)。 查看下面的FormatterRegistry SPI: package org.springframework.format; public interface FormatterRegistry extends ConverterRegistry { void addFormatterForFieldType(Class<?> fieldType, Printer<?> printer, Parser<?> parser); void addFormatterForFieldType(Class<?> fieldType, Formatter<?> formatter); void addFormatterForFieldType(Formatter<?> formatter); void addFormatterForAnnotation(AnnotationFormatterFactory<?, ?> factory); } 如上所示,格式化程序可以通过fieldType或注释进行注册。 FormatterRegistry SPI允许您集中配置格式化规则,而不是在控制器中复制这种配置。例如,您可能希望强制所有日期字段以特定方式格式化,或者使用特定批注的字段以特定方式格式化。通过共享的FormatterRegistry,您可以定义这些规则一次,并在需要格式化时应用这些规则。 4.FormatterRegistrar SPI FormatterRegistrar是一个用于通过FormatterRegistry注册格式化器和转换器的SPI: package org.springframework.format; public interface FormatterRegistrar { void registerFormatters(FormatterRegistry registry); } FormatterRegistrar在为给定格式类别(例如日期格式)注册多个相关转换器和格式化程序时非常有用。在声明性注册不足的情况下,它也很有用。例如,格式化程序需要在与其自己的不同的特定字段类型下或在注册打印机/解析器对时进行索引。下一节提供了有关转换器和格式化程序注册的更多信息。 三、配置全球日期和时间格式 默认情况下,不使用注释的日期和时间字段@DateTimeFormat使用DateFormat.SHORT样式从字符串转换。如果你愿意,你可以通过定义你自己的全局格式来改变它。 您需要确保Spring不会注册默认格式化程序,而应该手动注册所有格式化程序。根据您是否使用Joda-Time库,使用 org.springframework.format.datetime.joda.JodaTimeFormatterRegistraror或 org.springframework.format.datetime.DateFormatterRegistrarclass。 例如,以下Java配置将注册全局“yyyyMMdd”格式。这个例子不依赖于Joda-Time库: @Configuration public class AppConfig { @Bean public FormattingConversionService conversionService() { // Use the DefaultFormattingConversionService but do not register defaults DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(false); // Ensure @NumberFormat is still supported conversionService.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory()); // Register date conversion with a specific global format DateFormatterRegistrar registrar = new DateFormatterRegistrar(); registrar.setFormatter(new DateFormatter("yyyyMMdd")); registrar.registerFormatters(conversionService); return conversionService; } } 如果你更喜欢基于XML的配置,你可以使用a FormattingConversionServiceFactoryBean。这是同一个例子,这次使用乔达时间: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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.xsd> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="registerDefaultFormatters" value="false" /> <property name="formatters"> <set> <bean class="org.springframework.format.number.NumberFormatAnnotationFormatterFactory" /> </set> </property> <property name="formatterRegistrars"> <set> <bean class="org.springframework.format.datetime.joda.JodaTimeFormatterRegistrar"> <property name="dateFormatter"> <bean class="org.springframework.format.datetime.joda.DateTimeFormatterFactoryBean"> <property name="pattern" value="yyyyMMdd"/> </bean> </property> </bean> </set> </property> </bean> </beans> 乔达时提供单独的不同类型来表示date,time和date-time 的值。的dateFormatter,timeFormatter和dateTimeFormatter的性质 JodaTimeFormatterRegistrar,应使用来配置不同的格式为每种类型。在DateTimeFormatterFactoryBean提供了一个方便的方法来创建格式化。 如果您使用Spring MVC,请记住明确配置使用的转换服务。对于基于Java的@Configuration这意味着扩展 WebMvcConfigurationSupport类和重写mvcConversionService()方法。对于XML,您应该使用元素的’conversion-service’属性 mvc:annotation-driven。有关详细信息,请参阅转换和格式。

优秀的个人博客,低调大师

SpringFramework核心技术二:Resources(加载资源的几种方式)

Resources的介绍 java.net.URL不幸的是,对于各种URL前缀,Java的标准类和标准处理程序不足以满足所有对低级资源的访问。例如,没有URL可用于访问需要从类路径获取的资源的标准化实现,或者相对于某个资源的获取 ServletContext。尽管可以为专用URL 前缀注册新的处理程序(类似于诸如前缀的现有处理程序http:),但这通常非常复杂,并且URL界面仍然缺少某些期望的功能,例如检查资源是否存在的方法指出。 一、资源的接口 Spring的Resource界面旨在成为一个更强大的界面,用于抽象访问低级资源。 public interface Resource extends InputStreamSource { boolean exists(); boolean isOpen(); URL getURL() throws IOException; File getFile() throws IOException; Resource createRelative(String relativePath) throws IOException; String getFilename(); String getDescription(); } public interface InputStreamSource { InputStream getInputStream() throws IOException; } Resource接口中一些最重要的方法是: getInputStream():定位并打开资源,返回资源InputStream读取。预计每次调用都会返回一个新的 InputStream。主叫方有责任关闭该流。 exists():返回一个boolean指示这个资源是否实际存在的物理形式。 isOpen():返回一个boolean指示此资源是否表示具有打开流的句柄。如果true,则InputStream不能被多次读取,并且必须一次只能读取,然后关闭以避免资源泄漏。将false用于所有通常的资源实现,除了InputStreamResource。 getDescription():返回此资源的描述,用于处理资源时的错误输出。这通常是完全限定的文件名或资源的实际URL。 其他方法允许您获取表示资源的实际URL或File对象(如果底层实现兼容并支持该功能)。 该Resource抽象需要资源时Spring自身广泛使用,在许多方法签名的参数类型。在某些Spring API中的其他方法(比如各种ApplicationContext实现的构造函数),可以使用一种 String以未修改的或简单的形式创建Resource适合该上下文实现的String路径,或通过路径上的特殊前缀来允许调用者指定Resource必须创建和使用特定的实现。 尽管Resource接口在Spring和Spring中被大量使用,但是在您自己的代码中使用它作为一个通用工具类来访问资源,即使您的代码不知道或关心其他任何部件的春天。虽然这会将你的代码结合到Spring上,但它实际上只是将它连接到这套小实用程序类,这些实用程序类可用作更强大的替代品URL,并且可以认为它与您用于此目的的任何其他库相当。 重要的是要注意,Resource抽象并不取代功能:它尽可能包装它。例如,UrlResource封装一个URL,并使用包装URL来完成其工作。 二、Spring内置Resource接口的实现 Resource在Spring 中有很多实现可以直接使用: 1.UrlResource对象 所述UrlResource包裹一个java.net.URL,并且可以被用于访问任何对象,该对象是通过URL正常访问,如文件,一个HTTP靶,FTP对象等的所有URL具有标准化的String表示,以使得适当的标准化的前缀被用来指示从另一个URL类型。这包括file:访问文件系统路径,http:通过HTTP协议 ftp:访问资源,通过FTP访问资源等。 A UrlResource是由Java代码使用UrlResource构造函数显式创建的,但是当您调用一个API方法时,通常会隐式创建它,该方法需要一个String 用于表示路径的参数。对于后一种情况,JavaBeans PropertyEditor将最终决定Resource要创建哪种类型。如果路径字符串包含一些众所周知的(就是它)前缀,例如classpath:,它将Resource为该前缀创建适当的专用。但是,如果它不能识别前缀,它会认为这只是一个标准的URL字符串,并且会创建一个UrlResource。 2.使用ClassPathResource 这个类代表了一个应该从classpath中获取的资源。这使用线程上下文类加载器,给定的类加载器或给定的类来加载资源。 此Resource实现支持解析,就java.io.File好像类路径资源驻留在文件系统中一样,但不支持放置在jar中并且尚未扩展(通过servlet引擎或任何环境)扩展到文件系统的classpath资源。 为了解决这个问题,各种Resource实现总是支持解析java.net.URL。 A ClassPathResource是由Java代码使用ClassPathResource 构造函数显式创建的,但是当您调用一个API方法时,通常会隐式创建它,该方法需要一个String用于表示路径的参数。 对于后一种情况,JavaBeans PropertyEditor将识别classpath:字符串路径上的特殊前缀,并ClassPathResource在这种情况下创建一个。 3.FileSystemResource 这是一个句柄的Resource实现java.io.File。它显然支持作为一个File和作为一个决议URL。 4.ServletContextResource 这是资源的Resource实现ServletContext,解释相关Web应用程序根目录中的相对路径。 这总是支持流访问和URL访问,但只允许java.io.File在Web应用程序归档文件展开并且资源物理位于文件系统上时进行访问。不管它是否被扩展,并在文件系统上这样,或者直接从JAR或其他地方像DB(可以想象)访问,实际上都依赖于Servlet容器。 5.InputStreamResource Resource一个给定的实现InputStream。只有在没有具体的Resource实施方式的情况下才能使用。特别是,如果可能的话,更喜欢 ByteArrayResource或者任何基于文件的Resource实现。 相对于其他Resource的实现,这是一个描述符已经 打开资源-因此返回true的isOpen()。如果您需要将资源描述符保存在某处,或者您需要多次读取流,请不要使用它。 6.ByteArrayResource 这是Resource给定字节数组的一个实现。它ByteArrayInputStream为给定的字节数组创建一个 。 从任何给定的字节数组中加载内容是很有用的,而不必求助于单次使用InputStreamResource。 三、ResourceLoader(资源加载器) 该ResourceLoader接口意味着可以返回(即加载)Resource实例的对象来实现。 public interface ResourceLoader { Resource getResource(String location); } 所有应用程序上下文都实现该ResourceLoader接口,因此所有应用程序上下文都可用于获取Resource实例。 当您调用getResource()特定的应用程序上下文时,并且指定的位置路径没有特定的前缀时,您将返回Resource适合该特定应用程序上下文的类型。例如,假设针对一个ClassPathXmlApplicationContext实例执行了以下代码片段: Resource template = ctx.getResource("some/resource/path/myTemplate.txt"); 什么将返回将是一个ClassPathResource; 如果对一个FileSystemXmlApplicationContext实例执行相同的方法,你会得到一个 FileSystemResource。对于一个WebApplicationContext,你会回来 ServletContextResource,等等。 因此,您可以以适合特定应用程序上下文的方式加载资源。 另一方面,ClassPathResource通过指定特殊的classpath:前缀,你也可以强制使用,而不管应用程序的上下文类型如何: Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt"); 同样,可以UrlResource通过指定任何标准 java.net.URL前缀来强制使用a : Resource template = ctx.getResource("file:///some/resource/path/myTemplate.txt"); Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt"); 下表总结了将Strings 转换为Resources 的策略: Prefix Example Example classpath: classpath:com/myapp/config.xml Loaded from the classpath file: file:///data/config.xml Loaded as a URL, from the filesystem. [3] http: http://myserver/logo.png Loaded as a URL. (none) /data/config.xml Depends on the underlying ApplicationContext. 四、 The ResourceLoaderAware interface 该ResourceLoaderAware接口是一个特殊的标记接口,它希望被提供有对象ResourceLoader参考。 public interface ResourceLoaderAware { void setResourceLoader(ResourceLoader resourceLoader); } 当一个类实现ResourceLoaderAware并被部署到应用程序上下文中(作为一个Spring管理的bean)时,它被ResourceLoaderAware应用程序上下文识别。然后,应用程序上下文将调用 setResourceLoader(ResourceLoader),提供自己作为参数(请记住,Spring中的所有应用程序上下文实现该ResourceLoader接口)。 当然,因为a ApplicationContext是a ResourceLoader,所以bean也可以实现ApplicationContextAware接口并直接使用提供的应用程序上下文来加载资源,但是一般来说,ResourceLoader如果只需要这些,最好使用专用 接口。这些代码只会耦合到资源加载界面,它可以被认为是一个实用程序界面,而不是整个Spring ApplicationContext界面。 从Spring 2.5开始,您可以依靠自动装配ResourceLoader来实现ResourceLoaderAware接口。“传统” constructor和 byType自动装配模式(如自动装配协作者所描述的)现在能够分别为ResourceLoader构造函数参数或设置方法参数提供类型的依赖关系。为了获得更大的灵活性(包括自动装配字段和多个参数方法的能力),请考虑使用新的基于注释的自动装配功能。 下面这一句才是关键: 在这种情况下,只要字段,构造函数或方法带有 注释,ResourceLoader就会自动装入字段,构造函数参数或方法参数,该参数需要ResourceLoader类型@Autowired。有关更多信息,请参阅@Autowired。 五、资源作为依赖关系 如果bean本身要通过某种动态过程来确定并提供资源路径,那么bean可能会使用该ResourceLoader 接口来加载资源。考虑加载某种模板的例子,其中需要的特定资源取决于用户的角色。如果资源是静态的,那么ResourceLoader 完全消除接口的使用是有意义的,并且让bean暴露Resource它需要的属性,并期望它们被注入到它中。 什么使注入这些属性变得微不足道的是,所有的应用程序上下文都注册并使用一个特殊的JavaBeans PropertyEditor,它可以将String路径转换为Resource对象。因此,如果myBean具有类型的模板属性Resource,则可以使用该资源的简单字符串进行配置,如下所示: <bean id="myBean" class="..."> <property name="template" value="some/resource/path/myTemplate.txt"/> </bean> 需要注意的是资源路径没有前缀,是因为它本身是要在应用程序上下文中使用的ResourceLoader,这个资源会通过一个被加载 ClassPathResource,FileSystemResource或ServletContextResource(如适用)根据确切类型的上下文的。 如果需要强制使用特定Resource类型,则可以使用前缀。以下两个示例显示如何强制a ClassPathResource和a UrlResource(后者用于访问文件系统文件) <property name="template" value="classpath:some/resource/path/myTemplate.txt"> <property name="template" value="file:///some/resource/path/myTemplate.txt"/> 六、Application contexts and Resource paths(应用程序上下文和资源路径) 1.构建应用程序上下文 应用程序上下文构造函数(针对特定应用程序上下文类型)通常需要一个字符串或字符串数​​组作为资源的位置路径,以构成上下文定义的XML文件。 当这样的位置路径没有前缀时,Resource从该路径构建并用于加载bean定义的特定类型取决于特定的应用程序上下文,并且适用于特定的应用程序上下文。例如,如果您创建一个 ClassPathXmlApplicationContext如下: ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml"); ClassPathResource将使用a 将从类路径加载bean定义。但是,如果你创建一个FileSystemXmlApplicationContext如下: ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/appContext.xml"); bean定义将从文件系统位置加载,在这种情况下,相对于当前工作目录。 请注意,在位置路径上使用特殊类路径前缀或标准URL前缀将覆盖Resource为加载定义而创建的默认类型。所以这FileSystemXmlApplicationContext… ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:conf/appContext.xml"); 实际上会从类路径中加载它的bean定义。但是,它仍然是一个 FileSystemXmlApplicationContext。如果随后将其用作a ResourceLoader,则任何前缀不固定的路径仍将被视为文件系统路径。 2.构造ClassPathXmlApplicationContext实例 - 快捷方式 在ClassPathXmlApplicationContext提供了多种构造方法以便于实例。其基本思想是只提供一个字符串数组,它只包含XML文件本身的文件名(没有前导路径信息),另一个也提供一个Class; 在ClassPathXmlApplicationContext 将从给定类的路径信息。 有一个例子希望能够清楚地说明这一点。考虑一下这样的目录布局: com/ foo/ services.xml daos.xml MessengerService.class 一个ClassPathXmlApplicationContext由在’services.xml’和中定义的bean组成的 ‘daos.xml’实例可以像这样被实例化… ApplicationContext ctx = new ClassPathXmlApplicationContext( new String[] {"services.xml", "daos.xml"}, MessengerService.class); 3.应用程序上下文构造器资源路径中的通配符 应用上下文构造器值中的资源路径可以是简单的路径(如上所示),其具有到目标资源的一对一映射,或者可以包含特殊的“classpath *:”前缀和/或内部Ant-样式正则表达式(使用Spring的PathMatcher实用程序进行匹配)。后者都是有效的通配符 此机制的一个用途是在执行组件式应用程序组装时。所有组件都可以将上下文定义片段“发布”到众所周知的位置路径,并且当使用前缀相同的路径创建最终的应用上下文时 classpath*:,所有组件片段将被自动拾取。 请注意,此通配符特定于在应用程序上下文构造函数中使用资源路径(或PathMatcher直接使用实用程序类层次结构时),并在构建时解析。它与Resource类型本身无关。无法使用classpath*:前缀来构造实际Resource的资源,因为资源一次只能指向一个资源。 3.1. Ant-style Patterns(“/”分割的样式) 当路径位置包含Ant样式时,例如: /WEB-INF/*-context.xml com/mycompany/**/applicationContext.xml file:C:/some/path/*-context.xml classpath:com/mycompany/**/applicationContext.xml 解析器遵循更复杂但定义的过程来尝试解析通配符。它为直到最后一个非通配符段的路径生成一个资源,并从中获取一个URL。如果此URL不是jar:URL或特定zip:于容器的变体(例如,在WebLogic,wsjarWebSphere等中),java.io.File则从其中获得a 并通过遍历文件系统来解析通配符。在jar URL的情况下,解析器可以从中获取java.net.JarURLConnection或手动解析jar URL,然后遍历jar文件的内容来解析通配符。 3.2 对便携性的影响 如果指定的路径已经是文件URL(无论是显式地还是隐式地,因为基础ResourceLoader是文件系统),那么通配符将保证以完全便携的方式工作。 如果指定的路径是类路径位置,则解析器必须通过Classloader.getResource()调用获取最后一个非通配符路径段URL 。由于这只是路径的一个节点(不是最后的文件),所以ClassLoader在这种情况下,它实际上是未定义的(在 javadoc中)确切返回了哪种URL。实际上,它始终java.io.File代表目录,类路径资源解析为文件系统位置,或者某种类型的jar URL,其中classpath资源解析为jar位置。但是,这个操作仍然存在可移植性问题。 如果为最后一个非通配符段获取了一个jar URL,那么解析器必须能够java.net.JarURLConnection从其中获取a 或者手动解析jar URL,以便能够遍历jar的内容并解析通配符。这可以在大多数环境中使用,但在其他环境中会失败,强烈建议您在依赖特定环境之前彻底测试来自瓶子的资源的通配符解决方案。 4.类路径*:前缀 在构建基于XML的应用程序上下文时,位置字符串可能使用特殊的classpath*:前缀: ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:conf/appContext.xml"); 这个特殊的前缀指定必须获得与给定名称匹配的所有类路径资源(在内部,这基本上是通过ClassLoader.getResources(…​)调用发生的 ),然后进行合并以形成最终的应用程序上下文定义。 通配符类路径依赖于getResources()底层类加载器的方法。由于现在大多数应用程序服务器都提供它们自己的类加载器实现,所以在处理jar文件时行为可能会有所不同。一个简单的测试,以检查是否classpath*使用类加载器从classpath中的jar中加载文件: getClass().getClassLoader().getResources("<someFileInsideTheJar>")。使用具有相同名称但位于两个不同位置的文件进行此测试。如果返回的结果不正确,请检查应用程序服务器文档以了解可能影响类加载器行为的设置。 例如,classpath*:前缀也可以与PathMatcher位置路径其余部分的模式组合classpath*:META-INF/*-beans.xml。在这种情况下,解析策略非常简单:ClassLoader.getResources()在最后一个非通配符路径段上使用调用来获取类加载器层次结构中的所有匹配资源,然后关闭每个资源,然后使用上述相同的PathMatcher分解策略通配符子路径。 5.其他有关通配符的说明 请注意classpath*:,除非实际目标文件驻留在文件系统中,否则与Ant样式结合使用时,只能在模式启动前至少有一个根目录可靠地运行。这意味着类似的模式 classpath*:*.xml可能不会从jar文件的根目录中检索文件,而只能从扩展目录的根目录中检索文件。 Spring检索类路径条目的能力源于JDK的 ClassLoader.getResources()方法,该方法仅返回传入的空字符串的文件系统位置(指示可能的根搜索)。Spring也评估 URLClassLoader运行时配置和jar文件中的“java.class.path”清单,但这并不保证会导致可移植行为。 类路径包的扫描要求类路径中存在相应的目录条目。在使用Ant构建JAR时,请确保不要 激活JAR任务的仅文件开关。此外,在某些环境中,类路径目录可能不会基于安全策略公开,例如JDK 1.7.0_45和更高版本上的独立应用程序(这需要在您的清单中设置“受信任的库”;请参阅 http://stackoverflow.com/questions/ 19394570 / java-jre-7u45-breaks-classloader-getresources)。 在JDK 9的模块路径(Jigsaw)中,Spring的类路径扫描一般按预期工作。将资源放入专用目录也是非常值得推荐的,这样可以避免前面提到的在搜索jar文件根目录级别时的可移植性问题。 classpath:如果要在多个类路径位置中使用要搜索的根包,则不保证具有资源的Ant样式模式能够找到匹配的资源。这是因为资源如 com/mycompany/package1/service-context.xml may be in only one location, but when a path such as classpath:com/mycompany/**/service-context.xml 七、FileSystemResource警告 一个FileSystemResource未连接到FileSystemApplicationContext(即FileSystemApplicationContext不实际的ResourceLoader)将把绝对和相对路径如你所愿。相对路径是相对于当前工作目录的,而绝对路径是相对于文件系统的根。 为了向后兼容(历史)的原因然而,这改变时 FileSystemApplicationContext是ResourceLoader。在 FileSystemApplicationContext简单地让所有绑定的FileSystemResource情况下,把所有的位置路径为相对的,他们是否开始与斜线与否。实际上,这意味着以下内容是等同的:(区别在于conf前面是否需要”/”) ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/context.xml"); ApplicationContext ctx = new FileSystemXmlApplicationContext("/conf/context.xml"); 如下所示:(尽管它们有所不同,但一种情况是相对的,另一种是绝对的)。 FileSystemXmlApplicationContext ctx = ...; ctx.getResource("some/resource/path/myTemplate.txt"); FileSystemXmlApplicationContext ctx = ...; ctx.getResource("/some/resource/path/myTemplate.txt"); 在实践中,如果的确需要绝对的文件系统路径,最好是放弃使用绝对路径FileSystemResource/ FileSystemXmlApplicationContext,只是强制使用的UrlResource,通过使用file:URL前缀。 // actual context type doesn't matter, the Resource will always be UrlResource ctx.getResource("file:///some/resource/path/myTemplate.txt"); // force this FileSystemXmlApplicationContext to load its definition via a UrlResource ApplicationContext ctx = new FileSystemXmlApplicationContext("file:///conf/context.xml"); 好啦。Spring在加载资源的几种方式,就是目前这些东西了。

优秀的个人博客,低调大师

SpringFramework核心技术一(IOC:注册一个LoadTimeWeaver)

一、什么是LoadTimeWeaver 在LoadTimeWeaver用于由Spring动态变换的类,因为它们被装载到Java虚拟机(JVM)。 要启用加载时织入,请将其添加@EnableLoadTimeWeaving到您的某个 @Configuration类中: @Configuration @EnableLoadTimeWeaving public class AppConfig { } 或者对于XML配置,请使用以下context:load-time-weaver元素: <beans> <context:load-time-weaver/> </beans> 一旦配置为ApplicationContext。它内部的任何bean都ApplicationContext 可以实现LoadTimeWeaverAware,从而接收对加载时织机实例的引用。这与Spring的JPA支持相结合特别有用, 因为JPA类转换可能需要加载时织入。有关LocalContainerEntityManagerFactoryBean更多详细信息,请参阅javadocs。有关AspectJ加载时织入的更多信息,请参阅Spring框架中使用AspectJ进行加载时织入。 好了,注册一个LoadTimeWeaver就到这里啦。

优秀的个人博客,低调大师

SpringFramework核心技术一(IOC:基于Java的容器配置)

@Bean和@Configuration Spring新的Java配置支持中的中心构件是 - @Configuration注释类和@Bean注释方法。 一、基本概念:@Bean和@Configuration Spring新的Java配置支持中的中心构件是 - @Configuration注释类和@Bean注释方法。 该@Bean注释被用于指示一个方法实例,配置和初始化为通过Spring IoC容器进行管理的新对象。对于那些熟悉Spring的<beans/>XML配置的人来说,@Bean注释和<bean/>元素具有相同的作用。您可以在任何Spring中带@Component方法中使用@Bean,但是,它们通常与@Configurationbean一起使用。 使用注释类@Configuration表示它的主要目的是作为bean定义的来源。此外,@Configuration类允许通过简单地调用@Bean同一类中的其他方法来定义bean间依赖关系。最简单的@Configuration类可以读作如下: @Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } } AppConfig上面的类将等同于下面的Spring <beans/>XML: <beans> <bean id="myService" class="com.acme.services.MyServiceImpl"/> </beans> 二、Full @Configuration vs ‘lite’ @Bean mode? 当@Bean方法在没有@Configuration注释的类中被声明时,它们被称为在’精简’模式下处理。 在一个@Component或者一个普通的旧类中声明的Bean方法将被认为是’精简’的,其中包含类的一个不同的主要目的和一个@Bean方法仅仅是那里的一种奖励。 例如,服务组件可能会通过@Bean每个适用组件类的附加方法向集装箱公开管理视图。在这种情况下,@Bean方法是一个简单的通用工厂方法机制。 与完整不同@Configuration,lite @Bean方法不能声明bean间依赖关系。 相反,他们对包含组件的内部状态和可选的参数进行操作,它们可能会声明。 @Bean因此这种方法不应该引用其他 @Bean方法; 每个这样的方法实际上只是一个特定的bean引用的工厂方法,没有任何特殊的运行时语义。 这里的积极副作用是,在运行时不需要应用CGLIB子类,所以在类设计方面没有限制(即,包含的类可能是final等等)。 在常见的场景中,@Bean方法将在@Configuration类中声明,确保始终使用“完整”模式,并且跨方法引用将重定向到容器的生命周期管理。这样可以防止@Bean通过常规的Java调用意外调用相同的 方法,这有助于减少在“精简”模式下操作时难以追踪的细微错误。 三、使用AnnotationConfigApplicationContext实例化Spring容器 下面的部分介绍了Spring的AnnotationConfigApplicationContextSpring 3.0中的新功能。这种多功能的ApplicationContext实现不仅能够接受@Configuration类作为输入,还能够接受 @Component用JSR-330元数据注释的普通类和类。 当@Configuration提供类作为输入时,@Configuration类本身被注册为一个bean定义,并且在该类中所有@Bean声明的方法也被注册为bean定义。 当@Component被提供和JSR-330类,它们被登记为bean定义,并且假定DI元数据,例如@Autowired或者@Inject是这些类中使用的必要。 1.结构简单 与实例化Spring XML文件时用作输入的方式大致相同,在实例化一个类时 ClassPathXmlApplicationContext,@Configuration类可以用作输入AnnotationConfigApplicationContext。这允许完全无XML地使用Spring容器。 public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); MyService myService = ctx.getBean(MyService.class); myService.doStuff(); } 如上所述,AnnotationConfigApplicationContext不仅仅只适用于@Configuration注释的类。任何@Component or JSR-330注解类都可以作为输入提供给构造器,例如: public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(MyServiceImpl.class, Dependency1.class, Dependency2.class); MyService myService = ctx.getBean(MyService.class); myService.doStuff(); } 上面的MyServiceImpl、Dependency1和Dependency2类可以使用Spring依赖注入注释如@Autowired。 2.以编程的方式使用注册方法构造容器 一个AnnotationConfigApplicationContext可以使用无参数构造函数实例化,然后使用该register()方法进行配置。这种方法在编程构建一个AnnotationConfigApplicationContext。 public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AppConfig.class, OtherConfig.class); ctx.register(AdditionalConfig.class); ctx.refresh(); MyService myService = ctx.getBean(MyService.class); myService.doStuff(); } 3.使用@ComponentScan启用组件扫描 要启用组件扫描,只需@Configuration按照以下步骤注释您的班级: @Configuration @ComponentScan(basePackages = "com.acme") public class AppConfig { ... } 有经验的Spring用户将熟悉Spring的context:命名空间中的XML声明 <beans> <context:component-scan base-package="com.acme"/> </beans> 在上面的例子中,com.acme软件包将被扫描,寻找任何 @Component-annotated的类,并且这些类将被注册为容器中的Spring bean定义。AnnotationConfigApplicationContext公开该 scan(String…​)方法以允许相同的组件扫描功能: public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.scan("com.acme"); ctx.refresh(); MyService myService = ctx.getBean(MyService.class); } 请记住,@Configuration类是用元注释 的@Component,所以它们是组件扫描的候选对象!在上面的例子中,假设AppConfig在com.acme包(或下面的任何包)中声明了它,它将在调用过程中被拾取scan(),并且在refresh()其所有@Bean方法中将被处理并在容器中注册为bean定义。 4.在Web项目中使用AnnotationConfigWebApplicationContext 一个WebApplicationContext变体AnnotationConfigApplicationContext可用AnnotationConfigWebApplicationContext。当配置Spring ContextLoaderListenerservlet侦听器,Spring MVC DispatcherServlet等时,可以使用此实现。接下来是web.xml配置典型Spring MVC Web应用程序的片段。请注意使用contextClasscontext-param和init-param: <web-app> <!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext instead of the default XmlWebApplicationContext --> <context-param> <param-name>contextClass</param-name> <param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value> </context-param> <!-- Configuration locations must consist of one or more comma- or space-delimited fully-qualified @Configuration classes. Fully-qualified packages may also be specified for component-scanning --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>com.acme.AppConfig</param-value> </context-param> <!-- Bootstrap the root application context as usual using ContextLoaderListener --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Declare a Spring MVC DispatcherServlet as usual --> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext instead of the default XmlWebApplicationContext --> <init-param> <param-name>contextClass</param-name> <param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value> </init-param> <!-- Again, config locations must consist of one or more comma- or space-delimited and fully-qualified @Configuration classes --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>com.acme.web.MvcConfig</param-value> </init-param> </servlet> <!-- map all requests for /app/* to the dispatcher servlet --> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/app/*</url-pattern> </servlet-mapping> </web-app> 四、使用@Bean注释 @Bean是一种方法级别的注释和XML 元素的直接模拟。注释支持一些由其提供的属性<bean/>,例如: init-method, destroy-method, autowiring和name。 您可以在@Configuration或 @Component注释类中使用@Bean注解。 1.声明一个bean 要声明一个bean,只需使用注释对一个方法进行@Bean注释。您可以使用此方法在ApplicationContext指定为方法返回值的类型中注册一个bean定义。默认情况下,bean名称将与方法名称相同。以下是@Bean方法声明的一个简单示例: @Configuration public class AppConfig { @Bean public TransferServiceImpl transferService() { return new TransferServiceImpl(); } } 上述配置完全等同于以下Spring XML: <beans> <bean id="transferService" class="com.acme.TransferServiceImpl"/> </beans> 这两个声明都将一个名为transferService可用 的bean ApplicationContext,绑定到一个类型为object的对象实例TransferServiceImpl: transferService - > com.acme.TransferServiceImpl 你也可以@Bean用接口(或基类)返回类型声明你的方法: @Configuration public class AppConfig { @Bean public TransferService transferService() { return new TransferServiceImpl(); } } 但是,这会将提前类型预测的可见性限制为指定的接口类型(TransferService),然后,TransferServiceImpl一旦受影响的单例bean被实例化,容器就会知道完整类型()。非懒惰的singleton bean根据它们的声明顺序得到实例化,所以你可能会看到不同的类型匹配结果,这取决于另一个组件试图通过非声明类型进行匹配的时间(比如@Autowired TransferServiceImpl 只有在“transferService”bean已经被解析实例化)。 如果您始终通过声明的服务接口来引用您的类型,那么您的 @Bean返回类型可以安全地加入该设计决策。但是,对于实现多个接口的组件或可能由其实现类型引用的组件,声明最具体的返回类型是可能的(至少按照注入点对bean引用的要求)是比较安全的。 2.Bean依赖关系 @Bean注解的方法可以具有描述构建豆所需要的依赖关系的参数的任意数量。例如,如果我们TransferService 需要一个,AccountRepository我们可以通过一个方法参数来实现这个依赖关系: @Configuration public class AppConfig { @Bean public TransferService transferService(AccountRepository accountRepository) { return new TransferServiceImpl(accountRepository); } } 解析机制与基于构造函数的依赖注入非常相似。 3.接收生命周期回调 任何使用@Bean注释定义的类都支持常规生命周期回调,并且可以使用JSR-250中的注释@PostConstruct和@PreDestroy注释,请参阅 JSR-250注释以获取更多详细信息。 常规的Spring 生命周期回调也被完全支持。如果一个bean实现了InitializingBean,DisposableBean或者Lifecycle,它们各自的方法被容器调用。 *Aware诸如BeanFactoryAware, BeanNameAware, MessageSourceAware, ApplicationContextAware等的标准接口也完全受支持。 该@Bean注释支持指定任意初始化和销毁​​回调方法,就像Spring XML init-method和元素destroy-method上的属性一样bean: public class Foo { public void init() { // initialization logic } } public class Bar { public void cleanup() { // destruction logic } } @Configuration public class AppConfig { //初始化 @Bean(initMethod = "init") public Foo foo() { return new Foo(); } //销毁 @Bean(destroyMethod = "cleanup") public Bar bar() { return new Bar(); } } 默认情况下,使用具有公共close或shutdown 方法的Java配置定义的bean 将自动列入销毁回调。如果你有一个public close或shutdownmethod,并且你不希望在容器关闭时调用它,只需添加@Bean(destroyMethod=”“)到你的bean定义来禁用默认(inferred)模式。 您可能希望为通过JNDI获取的资源默认执行此操作,因为其生命周期在应用程序外部进行管理。特别是,确保始终DataSource以Java EE应用程序服务器上的问题着称。 @Bean(destroyMethod="") public DataSource dataSource() throws NamingException { return (DataSource) jndiTemplate.lookup("MyDS"); } 此外,通过@Bean方法,您通常会选择使用编程式JNDI查找:使用Spring的JndiTemplate/ JndiLocatorDelegatehelper或直接InitialContext使用JNDI ,但不会JndiObjectFactoryBean强制您将返回类型声明为FactoryBean类型而不是实际目标类型,很难在其他@Bean方法中用于参照所提供的资源的交叉引用调用。 当然,就上述情况而言, 在施工期间直接Foo调用该init()方法同样有效: @Configuration public class AppConfig { @Bean public Foo foo() { Foo foo = new Foo(); foo.init(); return foo; } // ... } 当您直接使用Java进行工作时,您可以对您的对象执行任何您喜欢的操作,并且不总是需要依赖容器生命周期! 4.指定bean作用域 使用@Scope注释 您可以指定使用@Bean注释定义的bean 应该具有特定的作用域。您可以使用Bean Scopes部分中指定的任何标准范围 。 默认范围是singleton,但您可以使用@Scope注释覆盖它: @Configuration public class MyConfiguration { @Bean @Scope("prototype") public Encryptor encryptor() { // ... } } @Scope和scoped-proxy Spring提供了一种通过作用域代理来处理作用域依赖关系的便捷方式 。在使用XML配置时创建此类代理的最简单方法就是元素。使用@Scope注释在Java中配置bean提供了与proxyMode属性等效的支持。默认值是no proxy(ScopedProxyMode.NO),但可以指定ScopedProxyMode.TARGET_CLASS或ScopedProxyMode.INTERFACES。 如果您将范围代理示例从XML参考文档(请参阅前面的链接)移植到我们@Bean使用的Java中,它将如下所示: // an HTTP Session-scoped bean exposed as a proxy @Bean @SessionScope public UserPreferences userPreferences() { return new UserPreferences(); } @Bean public Service userService() { UserService service = new SimpleUserService(); // a reference to the proxied userPreferences bean service.setUserPreferences(userPreferences()); return service; } 5.自定义bean命名 默认情况下,配置类使用@Bean方法的名称作为结果bean的名称。但是,可以使用该name属性覆盖此功能。 @Configuration public class AppConfig { @Bean(name = "myFoo") public Foo foo() { return new Foo(); } } 5.Bean别名 正如在命名bean中所讨论的,有时需要为单个bean提供多个名称,否则称为bean别名。 注解的name属性@Bean为此接受一个String数组。 @Configuration public class AppConfig { @Bean(name = { "dataSource", "subsystemA-dataSource", "subsystemB-dataSource" }) public DataSource dataSource() { // instantiate, configure and return DataSource bean... } } 6.Bean的描述 有时候提供一个更详细的bean的文本描述是有帮助的。当bean暴露(可能通过JMX)用于监视目的时,这可能特别有用。 为了说明添加到@Bean的 @Description 注释,可以使用: @Configuration public class AppConfig { @Bean @Description("Provides a basic example of a bean") public Foo foo() { return new Foo(); } } 五、使用@Configuration注释 @Configuration是一个类级注释,指示对象是bean定义的来源。@Configuration类通过公共@Bean注释方法声明bean 。调用@Bean的方法@Configuration类也可以用于定义bean间的依赖关系。有关一般介绍,请参阅基本概念:@Bean和@Configuration。 1.注入bean间依赖关系 当@Beans彼此依赖时,表达该依赖性就像一个bean方法调用另一个一样简单: @Configuration public class AppConfig { @Bean public Foo foo() { return new Foo(bar()); } @Bean public Bar bar() { return new Bar(); } } 在上面的例子中,foobean接收到bar通过构造函数注入的引用。 这种声明bean间依赖关系的@Bean方法只有在方法在@Configuration类中声明时才有效。您不能使用普通@Component类声明bean间依赖关系。 2.查找方法注入 如前所述,查找方法注入是一种您很少使用的高级功能。在单例范围的bean对原型范围的bean具有依赖关系的情况下,它很有用。对这种类型的配置使用Java提供了实现这种模式的自然方法。 public abstract class CommandManager { public Object process(Object commandState) { // grab a new instance of the appropriate Command interface Command command = createCommand(); // set the state on the (hopefully brand new) Command instance command.setState(commandState); return command.execute(); } // okay... but where is the implementation of this method? protected abstract Command createCommand(); } 使用Java配置支持,您可以创建CommandManager抽象createCommand()方法被重写的子类,以便查找新的(原型)命令对象: @Bean @Scope("prototype") public AsyncCommand asyncCommand() { AsyncCommand command = new AsyncCommand(); // inject dependencies here as required return command; } @Bean public CommandManager commandManager() { // return new anonymous implementation of CommandManager with command() overridden // to return a new prototype Command object return new CommandManager() { protected Command createCommand() { return asyncCommand(); } } } 六、有关基于Java的配置如何在内部工作的更多信息 以下示例显示了@Bean被调用两次的带注释的方法: @Configuration public class AppConfig { @Bean public ClientService clientService1() { ClientServiceImpl clientService = new ClientServiceImpl(); clientService.setClientDao(clientDao()); return clientService; } @Bean public ClientService clientService2() { ClientServiceImpl clientService = new ClientServiceImpl(); clientService.setClientDao(clientDao()); return clientService; } @Bean public ClientDao clientDao() { return new ClientDaoImpl(); } } clientDao()已被召入一次clientService1(),一次进入clientService2()。由于此方法创建ClientDaoImpl并返回它的新实例,因此通常期望拥有2个实例(每个服务一个实例)。这肯定会有问题:在Spring中,实例化的bean singleton默认具有一个范围。这就是魔法来临的地方:所有@Configuration类都在启动时被分类CGLIB。在子类中,child方法在调用父方法并创建新实例之前首先检查容器是否有缓存的(范围)Bean。请注意,从Spring 3.2开始,不再需要将CGLIB添加到类路径中,因为CGLIB类已被重新打包org.springframework.cglib并直接包含在Spring-core JAR中。 根据您的bean的范围,行为可能会有所不同。我们在这里讨论单身人士。 由于CGLIB在启动时动态添加功能,因此存在一些限制,特别是配置类不能是最终的。但是,从4.3开始,任何构造函数都可以在配置类上使用,包括@Autowired对默认注入使用 或使用单个非默认构造函数声明。 如果您更喜欢避免任何CGLIB强加的限制,请考虑@Bean 在非@Configuration类上声明您的方法,例如在普通@Component类上。方法之间的跨方法调用@Bean不会被拦截,因此您必须在构造方法或方法级别专门依赖依赖注入。 七、撰写基于Java的配置 1.使用@Import注释 就像Spring XML文件中使用该元素来帮助模块化配置一样,该@Import注释允许@Bean从另一个配置类加载定义: @Configuration public class ConfigA { @Bean public A a() { return new A(); } } @Configuration @Import(ConfigA.class) public class ConfigB { @Bean public B b() { return new B(); } } 现在,不需要指定两者ConfigA.class以及ConfigB.class何时实例化上下文,只ConfigB需要明确提供: public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class); // now both beans A and B will be available... A a = ctx.getBean(A.class); B b = ctx.getBean(B.class); } 这种方法简化了容器实例化,因为只有一个类需要处理,而不是要求开发人员@Configuration在构建过程中记住潜在的大量类。 从Spring Framework 4.2开始,它@Import也支持对常规组件类的引用,类似于该AnnotationConfigApplicationContext.register方法。如果您想要避免组件扫描,使用几个配置类作为明确定义所有组件的入口点,这特别有用。 2.注入对导入的@Bean定义的依赖关系 上面的例子工作,但是很简单。在大多数实际场景中,bean将跨配置类彼此依赖。当使用XML时,这本身并不是问题,因为不涉及编译器,并且可以简单地声明 ref=”someBean”并相信Spring将在容器初始化期间解决它。当然,在使用@Configuration类时,Java编译器会对配置模型施加约束,因为对其他bean的引用必须是有效的Java语法。 幸运的是,解决这个问题很简单。正如我们已经讨论过的, @Bean方法可以有任意数量的描述bean依赖关系的参数。让我们考虑一个更实际的场景,其中有几个@Configuration 类,每个类都依赖于其他类中声明的bean: @Configuration public class ServiceConfig { @Bean public TransferService transferService(AccountRepository accountRepository) { return new TransferServiceImpl(accountRepository); } } @Configuration public class RepositoryConfig { @Bean public AccountRepository accountRepository(DataSource dataSource) { return new JdbcAccountRepository(dataSource); } } @Configuration @Import({ServiceConfig.class, RepositoryConfig.class}) public class SystemTestConfig { @Bean public DataSource dataSource() { // return new DataSource } } public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(SystemTestConfig.class); // everything wires up across configuration classes... TransferService transferService = ctx.getBean(TransferService.class); transferService.transfer(100.00, "A123", "C456"); } 还有另一种方法可以实现相同的结果。请记住,@Configuration类最终只是容器中的另一个bean:这意味着它们可以像其他任何bean一样利用 @Autowired和@Value注入等! 确保以这种方式注入的依赖关系只有最简单的类型。@Configuration 类在上下文初始化期间处理得相当早,并且强制依赖性以这种方式注入可能会导致意外的早期初始化。在可能的情况下,采用基于参数的注入,如上例所示。 另外,要特别小心,BeanPostProcessor并BeanFactoryPostProcessor通过定义@Bean。这些通常应该声明为static @Bean方法,而不是触发其包含的配置类的实例化。否则,@Autowired它@Value不会在配置类本身上工作,因为它太早创建为bean实例。 @Configuration public class ServiceConfig { @Autowired private AccountRepository accountRepository; @Bean public TransferService transferService() { return new TransferServiceImpl(accountRepository); } } @Configuration public class RepositoryConfig { private final DataSource dataSource; @Autowired public RepositoryConfig(DataSource dataSource) { this.dataSource = dataSource; } @Bean public AccountRepository accountRepository() { return new JdbcAccountRepository(dataSource); } } @Configuration @Import({ServiceConfig.class, RepositoryConfig.class}) public class SystemTestConfig { @Bean public DataSource dataSource() { // return new DataSource } } public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(SystemTestConfig.class); // everything wires up across configuration classes... TransferService transferService = ctx.getBean(TransferService.class); transferService.transfer(100.00, "A123", "C456"); } @Configuration类的构造器注入仅在Spring Framework 4.3中受支持。还要注意,不需要指定@Autowired目标bean是否只定义了一个构造函数; 在上面的例子中,@Autowired在RepositoryConfig构造函数中是没有必要的。 1.完全限定导入的豆类以便导航 在上面的场景中,使用得@Autowired很好,并提供了所需的模块化,但是确切地确定自动布线bean定义的声明位置仍然有些模糊。例如,作为一名开发人员ServiceConfig,您如何知道@Autowired AccountRepositorybean的确切位置?它在代码中并不明确,这可能会很好。请记住, Spring Tool Suite提供的工具可以呈现图表,显示如何连接所有东西 - 这可能就是您所需要的一切。此外,您的Java IDE可以轻松找到该AccountRepository类型的所有声明和用法,并会快速向您显示@Bean返回该类型的方法的位置。 如果这种不明确性不可接受,并且希望从IDE内部直接导航@Configuration到另一个类,请考虑自动配置自己的配置类: @Configuration public class ServiceConfig { @Autowired private RepositoryConfig repositoryConfig; @Bean public TransferService transferService() { // navigate 'through' the config class to the @Bean method! return new TransferServiceImpl(repositoryConfig.accountRepository()); } } 在上面的情况中,它是完全明确的,在哪里AccountRepository定义。但是,ServiceConfig现在紧紧耦合在一起RepositoryConfig; 这是权衡。通过使用基于接口的类或基于抽象的基于@Configuration类的类,可以稍微缓解这种紧密耦合。考虑以下: @Configuration public class ServiceConfig { @Autowired private RepositoryConfig repositoryConfig; @Bean public TransferService transferService() { return new TransferServiceImpl(repositoryConfig.accountRepository()); } } @Configuration public interface RepositoryConfig { @Bean AccountRepository accountRepository(); } @Configuration public class DefaultRepositoryConfig implements RepositoryConfig { @Bean public AccountRepository accountRepository() { return new JdbcAccountRepository(...); } } @Configuration @Import({ServiceConfig.class, DefaultRepositoryConfig.class}) // import the concrete config! public class SystemTestConfig { @Bean public DataSource dataSource() { // return DataSource } } public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(SystemTestConfig.class); TransferService transferService = ctx.getBean(TransferService.class); transferService.transfer(100.00, "A123", "C456"); } 现在ServiceConfig与具体方面松散耦合 DefaultRepositoryConfig,并且内置的IDE工具仍然有用:开发人员可以轻松获得类型层次结构的RepositoryConfig实现。通过这种方式,导航@Configuration类及其依赖关系与导航基于接口的代码的常用过程无异。 如果你想影响某些豆类的启动创建顺序,考虑宣布一些为@Lazy(对于第一次访问,而不是在启动时创建)或@DependsOn某些其它豆类(确保特定的其他豆将在当前之前创建bean,超越了后者的直接依赖意味)。 二、有条件地包含@Configuration类或@Bean方法 根据某些任意系统状态,有条件地启用或禁用完整的@Configuration类,甚至个别的@Bean方法通常很有用。一个常见的例子是,@Profile只有在Spring中启用了特定的配置文件时才使用注释来激活bean Environment(请参阅Bean定义配置文件 以了解详细信息)。 该@Profile注释是使用所谓的更灵活的注释实际执行@Conditional。该@Conditional注释指示特定 org.springframework.context.annotation.Condition前应谘询的实施@Bean是注册。 Condition接口的实现只是提供了一个matches(…​) 返回true或返回的方法false。例如,以下是Condition用于以下内容的实际 实现@Profile: @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { if (context.getEnvironment() != null) { // Read the @Profile annotation attributes MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName()); if (attrs != null) { for (Object value : attrs.get("value")) { if (context.getEnvironment().acceptsProfiles(((String[]) value))) { return true; } } return false; } } return true; } 八、结合Java和XML配置 Spring的@Configuration类支持并不旨在成为Spring XML的100%完全替代品。Spring XML命名空间等一些工具仍然是配置容器的理想方式。在XML方便或必要的情况下,您可以选择:或者使用“以XML为中心”的方式实例化容器ClassPathXmlApplicationContext,或者使用“以Java为中心”的方式 实例化容器, AnnotationConfigApplicationContext并使用@ImportResource注释根据需要导入XML 。 1.以XML为中心使用@Configuration类 最好从XML引导Spring容器,并@Configuration以临时方式包含 类。例如,在使用Spring XML的大型现有代码库中,根据需要创建@Configuration类并从现有XML文件中包含它们会更容易。下面你会发现@Configuration在这种“以XML为中心”的情况下使用类的选项。 将@Configuration类声明为普通的Spring <bean/>元素 请记住,@Configuration类最终只是容器中的bean定义。在这个例子中,我们创建一个@Configuration名为AppConfig并包含它的类system-test-config.xml作为<bean/>定义。因为<context:annotation-config/>已打开,容器将识别 @Configuration注释并处理 正确@Bean声明的方法AppConfig。 @Configuration public class AppConfig { @Autowired private DataSource dataSource; @Bean public AccountRepository accountRepository() { return new JdbcAccountRepository(dataSource); } @Bean public TransferService transferService() { return new TransferService(accountRepository()); } } system-test-config.xml: <beans> <!-- enable processing of annotations such as @Autowired and @Configuration --> <context:annotation-config/> <context:property-placeholder location="classpath:/com/acme/jdbc.properties"/> <bean class="com.acme.AppConfig"/> <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> </beans> jdbc.properties: jdbc.url = JDBC:HSQLDB:HSQL://本地主机/ XDB jdbc.username = SA jdbc.password = public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:/com/acme/system-test-config.xml"); TransferService transferService = ctx.getBean(TransferService.class); // ... } 在system-test-config.xml上面,AppConfig <bean/>没有声明一个id 元素。虽然这样做是可以接受的,但没有必要考虑到其他bean将不会引用它,并且它不太可能通过名称明确从容器中提取。与DataSourcebean 同样- 它只能通过类型自动装配,因此id不需要显式bean 。 使用<context:component-scan />来拾取@Configuration类 因为@Configuration与间注解@Component,@Configuration-annotated类自动对于组件扫描的候选者。使用与上述相同的场景,我们可以重新定义system-test-config.xml以利用组件扫描。请注意,在这种情况下,我们不需要显式声明 <context:annotation-config/>,因为<context:component-scan/>启用了相同的功能。 <beans> <!-- picks up and registers AppConfig as a bean definition --> <context:component-scan base-package="com.acme"/> <context:property-placeholder location="classpath:/com/acme/jdbc.properties"/> <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> </beans> 2.@Configuration以@ImportResource为中心使用XML 在@Configuration类是用于配置容器的主要机制的应用程序中,仍然可能有必要使用至少一些XML。在这些场景中,只需使用@ImportResource和定义尽可能多的XML即可。这样做可以实现“以Java为中心”的方式来配置容器,并将XML保持最低限度。 @Configuration @ImportResource("classpath:/com/acme/properties-config.xml") public class AppConfig { @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean public DataSource dataSource() { return new DriverManagerDataSource(url, username, password); } } properties-config.xml <beans> <context:property-placeholder location="classpath:/com/acme/jdbc.properties"/> </beans> jdbc.properties jdbc.url = JDBC:HSQLDB:HSQL://本地主机/ XDB jdbc.username = SA jdbc.password = main public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); TransferService transferService = ctx.getBean(TransferService.class); // ... } 好啦,基于Java的容器配置讲了这么多,总算是完啦。 加油啦,越努力越幸运

优秀的个人博客,低调大师

【技术干货】剖析pip ssh-decorate供应链攻击

文/图 阿里安全猎户座实验室 近日,国外媒体有安全人员爆出Python pip ssh-decorate被发现存在后门代码!对,又是pip污染。 pip是python的开源包资源库。然而,这个开源库的管理是十分松散的。尤其在安全方面并没有严格的审核机制。一个用户只需要一个email即可注册账户,然后即可上传其源文件到pip资源中。而这个pip资源是被世界上所有python用户使用下载的。如果有人夹杂恶意代码上传了某个包,并以常见程序的名字命名,比如zip,ssh,smb,ftp。那么当有用户尝试搜索并下载使用这个名字的包时,这个用户就会中招,可谓神不知鬼不觉。这就是存在于pip中的供应链安全问题。回头看,针对pip的攻击已经并不新鲜,早在几年前就有国外研究者进行过类似实验。而真正让大家重视起来是在2017年,国内白帽子也针对pip源进

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

用户登录
用户注册
修改密码
忘记密码