一、Configuration

@ImportResource结合xml使用

  1. @Configuration
  2. @ImportResource("classpath:/com/acme/properties-config.xml")
  3. public class AppConfig {
  4. @Value("${jdbc.url}")
  5. private String url;
  6. @Value("${jdbc.username}")
  7. private String username;
  8. @Value("${jdbc.password}")
  9. private String password;
  10. @Bean
  11. public DataSource dataSource() {
  12. return new DriverManagerDataSource(url, username, password);
  13. }
  14. }

@PropertySource

  1. @Configuration
  2. @PropertySource("classpath:/com/myco/app.properties")
  3. public class AppConfig {
  4. //直接使用env因为配置文件
  5. @Autowired
  6. Environment env;
  7. @Bean
  8. public TestBean testBean() {
  9. TestBean testBean = new TestBean();
  10. testBean.setName(env.getProperty("testbean.name"));
  11. return testBean;
  12. }
  13. }

LoadTimeWeaver
将@EnableLoadTimeWeaving添加到一个@Configuration classes

@Configuration
@EnableLoadTimeWeaving
public class AppConfig {
}
//xml配置
<beans>
    <context:load-time-weaver/>
</beans>

二、使用MessageSource国际化

Spring 提供两个**MessageSource** implementations,**ResourceBundleMessageSource**和**StaticMessageSource**。
下面是静态资源方式(很少使用.)

<beans>
    <bean id="messageSource"
            class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>format</value>
                <value>exceptions</value>
                <value>windows</value>
            </list>
        </property>
    </bean>
</beans>

编程方式显示:

message=Alligators rock!
argument.required=The {0} argument is required.
# in exceptions_en_GB.properties 英国版
argument.required=Ebagum lad, the {0} argument is required, I say, required.
public static void main(String[] args) {
    MessageSource resources = new ClassPathXmlApplicationContext("beans.xml");
    String message = resources.getMessage("message", null, "Default", null);
    System.out.println(message);
    //输出Alligators rock!
}
public class Example {

    private MessageSource messages;

    public void setMessages(MessageSource messages) {
        this.messages = messages;
    }

    public void execute() {
        String message = this.messages.getMessage("argument.required",
            new Object [] {"userDao"}, "Required", null);
        System.out.println(message);
        //输出The userDao argument is required.
    }
    //调用其他版本
    public static void main(final String[] args) {
    MessageSource resources = new ClassPathXmlApplicationContext("beans.xml");
    String message = resources.getMessage("argument.required",
        new Object [] {"userDao"}, "Required", Locale.UK);
    System.out.println(message);
        //输出Ebagum lad, the 'userDao' argument is required, I say, required.
}
}

三、标准事件和自定义事件

事件 说明
ContextRefreshedEvent 初始化或刷新ApplicationContext
时发布(对于 example,通过ConfigurableApplicationContext
接口使用refresh()
方法)。这里,“初始化”意味着所有 beans 都被加载,post-processor beans 被检测并激活,单例是 pre-instantiated,ApplicationContext
object 可以使用了。如果 context 尚未关闭_long,则可以多次触发刷新,前提是所选的ApplicationContext
实际上支持这种“热”刷新。对于 example,XmlWebApplicationContext
支持热刷新,但GenericApplicationContext
不支持。
ContextStartedEvent 通过在ConfigurableApplicationContext
接口上使用start()
方法启动ApplicationContext
时发布。这里,“已启动”意味着所有Lifecycle
beans 都会收到明确的启动信号。通常,此信号用于在显式停止后重新启动 beans,但它也可用于启动尚未为自动启动配置的组件(对于 example,尚未在初始化时启动的组件)。
ContextStoppedEvent 通过在ConfigurableApplicationContext
接口上使用stop()
方法停止ApplicationContext
时发布。这里,“停止”意味着所有Lifecycle
beans 都会收到明确的停止信号。可以通过start()
调用重新启动已停止的 context。
ContextClosedEvent 通过在ConfigurableApplicationContext
接口上使用close()
方法关闭ApplicationContext
时发布。在这里,“关闭”意味着所有 singleton beans 都被销毁。封闭的 context 到达其生命的终点。它无法刷新或重新启动。
RequestHandledEvent web-specific event 告诉所有 beans 已经为 HTTP 请求提供服务。请求完成后发布此 event。此 event 仅适用于使用 Spring 的DispatcherServlet
的 web applications。

3.1 @EventListener 类型监听

public class BlackListNotifier {

    private String notificationAddress;

    public void setNotificationAddress(String notificationAddress) {
        this.notificationAddress = notificationAddress;
    }
    //监听单个类
    @EventListener
    public void processBlackListEvent(BlackListEvent event) {
        // notify appropriate parties via notificationAddress...
    }    
    //监听多个类
    @EventListener({ContextStartedEvent.class, ContextRefreshedEvent.class})
    public void handleContextStart() {
        ...
    }
}

还可以通过使用定义SpEL 表达的 annotation 的condition属性来添加额外的运行时过滤,应该 match 以实际调用特定 event 的方法。

/**只有 event 的content属性等于my-event时才能重写我们的通知程序才能被调用*/
@EventListener(condition = "#blEvent.content == 'my-event'")
public void processBlackListEvent(BlackListEvent blEvent) {
    // notify appropriate parties via notificationAddress...
}

异步 Listeners
添加 async

@EventListener
@Async
public void processBlackListEvent(BlackListEvent event) {
    // BlackListEvent is processed in a separate thread
}

使用异步 events 时请注意以下限制:

  • 如果 event listener 抛出Exception,则它不会传播给调用者有关详细信息,请参阅AsyncUncaughtExceptionHandler。
  • 这样的 event listener 无法发送回复。如果您需要作为处理结果发送另一个 event,inject ApplicationEventPublisher手动发送 event。

可以添加@Order 在调用前调用另外一个listener

四、Resource

Resource接口定义:

public interface Resource extends InputStreamSource {

    //判断资源是否存在于物理形式中
    boolean exists();
    //指示此资源是否表示具有开放流的句柄。如果true,InputStream不能多次读取,
    //必须只读一次然后关闭以避免资源泄漏。对于所有常用资源 implementations,返回false,的 exception。
    boolean isOpen();

    URL getURL() throws IOException;

    File getFile() throws IOException;

    Resource createRelative(String relativePath) throws IOException;

    String getFilename();

    //获得资源的描述
    String getDescription();
    //下面是继承的
    //找到并打开资源,返回InputStream以从资源中读取。预计每次调用都会返回一个新的InputStream。
    InputStream getInputStream() throws IOException;
}

public interface InputStreamSource {

    InputStream getInputStream() throws IOException;

}

实现类:

  • UrlResource
  • ClassPathResource
  • FileSystemResource
  • ServletContextResource
  • InputStreamResource
  • ByteArrayResource

    4.1 UrlResource

    UrlResource包装java.net.URL,可用于访问通常可通过 URL 访问的任何 object,例如 files,HTTP 目标,FTP 目标等。所有 URL 都具有标准化的String表示,使得适当的标准化前缀用于指示来自另一个的一种 URL 类型。这包括file:用于访问文件系统_path,http:用于通过 HTTP 协议访问资源,ftp:用于通过 FTP 访问资源,以及其他。
    是由 Java code 通过显式使用UrlResource构造函数创建的,但是当您调用一个带有String参数的 API 方法来表示路径时,通常会隐式创建UrlResource。对于后一种情况,JavaBeans PropertyEditor最终决定创建哪种类型的Resource。如果路径 string 包含 well-known(对它,那是)前缀(例如classpath:),它会为该前缀创建一个适当的专用Resource。但是,如果它不识别前缀,则假定 string 是标准 URL string 并创建UrlResource。

    4.2 ClassPathResource

    此 class 表示应从 classpath 获取的资源。它使用线程 context class 加载器,给定的 class 加载器或给定 class 来加载 loading 资源。
    如果 class 路径资源驻留在文件系统中,而 classpath 资源驻留在 jar 中并且尚未(通过 servlet 引擎或任何环境)扩展到文件系统,则此Resource implementation 支持解析为java.io.File。为了解决这个问题,各种Resource implementations 总是支持解析为java.net.URL。
    是由 Java code 通过显式使用ClassPathResource构造函数创建的,但是当您调用一个带有String参数的 API 方法来表示路径时,通常会隐式创建ClassPathResource。对于后一种情况,JavaBeans PropertyEditor在 string 路径上识别特殊前缀classpath:,并在这种情况下创建ClassPathResource。

    4.3 ResourceLoader

    ResourceLoader接口应由 objects 实现,它可以 return(即加载)Resource实例。以下清单显示了ResourceLoader接口定义 ```java public interface ResourceLoader {

    Resource getResource(String location);

} //使用如下 Resource template = ctx.getResource(“some/resource/path/myTemplate.txt”);

 创建**Application** 的时候
```java
ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml");
//或者,不过这个是位于当前目录下的
ApplicationContext ctx =
    new FileSystemXmlApplicationContext("conf/appContext.xml");

//位于classpath路劲下的
ApplicationContext ctx =
    new FileSystemXmlApplicationContext("classpath:conf/appContext.xml");

4.4 Application Context 构造函数资源 Paths

Ant-style 模式

/WEB-INF/*-context.xml
com/mycompany/**/applicationContext.xml
file:C:/some/path/*-context.xml
classpath:com/mycompany/**/applicationContext.xml

classpath *:前缀
此特殊前缀指定必须获取 match 给定 name 的所有 classpath 资源(内部,这通常通过调用ClassLoader.getResources(…))然后合并以形成最终的 application context 定义
classpath*:与 Ant-style 模式结合使用时,只能在 pattern 启动之前与至少一个根目录可靠地工作,除非实际目标 files 位于文件系统中。这意味着诸如classpath*:*.xml之类的 pattern 可能无法从 jar files 的根目录中检索 files,而只能从扩展目录的根目录中检索 files。

FileSystemResource

由于某种原因无论是否以/开头,都是使用先对路径。

ApplicationContext ctx =
    new FileSystemXmlApplicationContext("conf/context.xml");
ApplicationContext ctx =
    new FileSystemXmlApplicationContext("/conf/context.xml");
//绝对路径如下写法:
ApplicationContext ctx =
    new FileSystemXmlApplicationContext("file:///conf/context.xml");

五、数据校验

通过实现org.springframework.validation.Validator接口的以下两个方法为 class 提供验证行为。

  - `supports(Class)`:这可以`Validator`验证提供的`Class`的实例
  - `validate(Object, org.springframework.validation.Errors)`:验证给定的 object,并在验证错误的情况下,使用给定的`Errors` object 注册那些。
public class PersonValidator implements Validator {

    /**
     * This Validator validates *only* Person instances
     */
    public boolean supports(Class clazz) {
        return Person.class.equals(clazz);
    }

    public void validate(Object obj, Errors e) {
        ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
        Person p = (Person) obj;
        if (p.getAge() < 0) {
            e.rejectValue("age", "negativevalue");
        } else if (p.getAge() > 110) {
            e.rejectValue("age", "too.darn.old");
        }
    }
}

原生的太麻烦,后续补充。

public class PersonForm {

    @NotNull
    @Size(max=64)
    private String name;

    @Min(0)
    private int age;
}

配置自定义约束

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
//指定实现的类
@Constraint(validatedBy=MyConstraintValidator.class)
public @interface MyConstraint {
}

import javax.validation.ConstraintValidator;

public class MyConstraintValidator implements ConstraintValidator {

    @Autowired;
    private Foo aDependency;

    ...
}

Spring-driven 方法验证
您可以通过MethodValidationPostProcessor bean 定义将 Bean Validation 1.1 支持的方法验证 feature(以及作为自定义扩展,也可以通过 Hibernate Validator 4.3)集成到 Spring context 中,如下所示:

<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/>

要符合 Spring-driven 方法验证的条件,所有目标 classes 都需要使用 Spring 的@Validated annotation 进行注释。 (或者,您也可以将验证组声明为 use.)使用 Hibernate Validator 和 Bean Validation 1.1 提供程序查看MethodValidationPostProcessor javadoc 以获取设置详细信息。

其他 获取 properties

设置和获取 properties 是通过使用带有几个重载变体的setPropertyValue,setPropertyValues,getPropertyValue和getPropertyValues
使用SPEL 获取字段属性,

 @Value("#{ systemProperties['user.region'] }")
 private String defaultLocale;
//同时也可以注解在方法字段上

六、Spring 类型转换

….
不会很懂

七、格式化注解API

可以使用@NumberFormat格式化 java.lang.Number 字段,使用@DateTimeFormat格式化java.util.Date,java.util.Calendar,java.util.Long或 Joda-Time 字段

public class MyModel {
    //java.util.Date格式化为 ISO Date(yyyy-MM-dd)
    @DateTimeFormat(iso=ISO.DATE)
    private Date date;
}

配置 Global Date 和 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;
    }
}