Spring IOC

来源:互联网 发布:龙卷风流量软件下载 编辑:程序博客网 时间:2024/06/03 23:04

这里写图片描述

ApplicationContext

依赖的包

  • org.springframework.beans
  • org.springframework.context

ApplicationContext

这个是提供接口的核心,它还有个直接子接口WebApplicationContext

这里写图片描述

可以直接使用的实现类有:ClassPathXmlApplicationContext 或者FileSystemXmlApplicationContext

下图是原理图:

这里写图片描述

初始化一个容器并配置

//使用XmlApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");//使用Kotlin DSLfun beans() = beans {  bean<UserHandler>()  bean<Routes>()  bean<WebHandler>("webHandler") {    RouterFunctions.toWebHandler(      ref<Routes>().router(),      HandlerStrategies.builder().viewResolver(ref()).build()    )  }  bean("messageSource") {    ReloadableResourceBundleMessageSource().apply {      setBasename("messages")      setDefaultEncoding("UTF-8")    }  }  bean {    val prefix = "classpath:/templates/"    val suffix = ".mustache"    val loader = MustacheResourceTemplateLoader(prefix, suffix)    MustacheViewResolver(Mustache.compiler().withLoader(loader)).apply {      setPrefix(prefix)      setSuffix(suffix)    }  }  profile("foo") {    bean<Foo>()  }}

使用ApplicationContext

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");//ApplicationContext context = new GenericGroovyApplicationContext("services.groovy", "daos.groovy");// retrieve configured instancePetStoreService service = context.getBean("petStore", PetStoreService.class);// use configured instanceList<String> userList = service.getUsernameList();

Bean定义的依赖

这里写图片描述

//class和name<bean id="exampleBean" class="examples.ExampleBean"/><bean name="anotherExample" class="examples.ExampleBeanTwo"/><bean id="clientService"        factory-bean="serviceLocator"        factory-method="createClientServiceInstance"/>public class DefaultServiceLocator {        private static ClientService clientService = new ClientServiceImpl();        public ClientService createClientServiceInstance() {                return clientService;        }}<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">        <property name="locations" value="classpath:com/foo/jdbc.properties"/></bean><bean id="dataSource" destroy-method="close"                class="org.apache.commons.dbcp.BasicDataSource">        <property name="driverClassName" value="${jdbc.driverClassName}"/>        <property name="url" value="${jdbc.url}"/>        <property name="username" value="${jdbc.username}"/>        <property name="password" value="${jdbc.password}"/></bean>jdbc.driverClassName=org.hsqldb.jdbcDriverjdbc.url=jdbc:hsqldb:hsql://production:9002jdbc.username=sajdbc.password=root

作用域

这里写图片描述

@SessionScope@RequestScope@ApplicationScope@Scope#SCOPE_PROTOTYPE#SCOPE_SINGLETON#SCOPE_REQUEST#SCOPE_SESSION

注解配置

<?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.xsd">        <context:annotation-config/></beans>@Required/@Resource: setter注入@Autowired:setter,构造器,方法,private属性,Map,List注入@Configurationpublic class MovieConfiguration {        @Bean        @Primary        public MovieCatalog firstMovieCatalog() { ... }        @Bean        public MovieCatalog secondMovieCatalog() { ... }        // ...}@Qualifier: value为一个修饰词,注入时也要使用一样的修饰@PostConstruct:注解作为初始化方法,初始化后调用@PreDestroy:注解作为销毁方法,销毁前调用@Component:作为Bean的类,是下面几个的父注解@Repository:作为持久层的组件@Service:作为服务层的组件@Controller:作为控制器的组件@Configuration:作为Java配置类的注解@ComponentScan(basePackages = "org.example"):与@Configuration合用,用于自动发现Component,可代替xml的标签@Import(ConfigA.class):引入别的配置文件@ImportResource("classpath:/com/acme/properties-config.xml")@PropertySource("classpath:/com/myco/app.properties"):引入配置

@ComponentScan的过滤器

这里写图片描述

   @Configuration   @ComponentScan(basePackages = "org.example",                   includeFilters = @Filter(type = FilterType.REGEX, pattern = ".*Stub.*Repository"),                   excludeFilters = @Filter(Repository.class))   public class AppConfig {        @Bean        @Description("Provides a basic example of a bean")        public Foo foo() {                return new Foo();        }   }

配置文件

@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.propertiesjdbc.propertiesjdbc.url=jdbc:hsqldb:hsql://localhost/xdbjdbc.username=sajdbc.password=//或者直接引入properties文件@Configuration@PropertySource("classpath:/com/myco/app.properties")public class AppConfig { @Autowired Environment env; @Bean public TestBean testBean() {  TestBean testBean = new TestBean();  testBean.setName(env.getProperty("testbean.name"));  return testBean; }}

环境配置

//开发环境@Configuration@Profile("development")public class StandaloneDataConfig {        @Bean        public DataSource dataSource() {                return new EmbeddedDatabaseBuilder()                        .setType(EmbeddedDatabaseType.HSQL)                        .addScript("classpath:com/bank/config/sql/schema.sql")                        .addScript("classpath:com/bank/config/sql/test-data.sql")                        .build();        }}//生产环境@Configuration@Profile("production")public class JndiDataConfig {        @Bean(destroyMethod="")        public DataSource dataSource() throws Exception {                Context ctx = new InitialContext();                return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");        }}

其他注解

@EnableLoadTimeWeaving:加载到虚拟机的时候织入AOP

Spring事件

Context事件有:ContextRefreshedEvent, ContextStartedEvent, ContextStoppedEvent, ContextClosedEvent, RequestHandledEvent

自定义事件

//事件public class BlackListEvent extends ApplicationEvent {        private final String address;        private final String test;        public BlackListEvent(Object source, String address, String test) {                super(source);                this.address = address;                this.test = test;        }        // accessor and other methods...}//事件发布器实现类:接口方法是setApplicationEventPublisher//而ApplicationEventPublisher类则有void publishEvent(Object event);用于发送事件public class EmailService implements ApplicationEventPublisherAware {        private List<String> blackList;        private ApplicationEventPublisher publisher;        public void setBlackList(List<String> blackList) {                this.blackList = blackList;        }        public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {                this.publisher = publisher;        }        public void sendEmail(String address, String text) {                if (blackList.contains(address)) {                        BlackListEvent event = new BlackListEvent(this, address, text);                        publisher.publishEvent(event);                        return;                }                // send email...        }}//监听器public class BlackListNotifier implements ApplicationListener<BlackListEvent> {        private String notificationAddress;        public void setNotificationAddress(String notificationAddress) {                this.notificationAddress = notificationAddress;        }        //@EventListener      监听BlackListEvent        @EventListener(condition = "#blEvent.test == 'foo'")        @Async   //可以选择以异步方式来处理事件        @Order(42) //以顺序的方式处理事件        public void processBlackListEvent(BlackListEvent event) {                // notify appropriate parties via notificationAddress...        }}

Resource

Resource template = ctx.getResource("some/resource/path/myTemplate.txt");Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");Resource template = ctx.getResource("file:///some/resource/path/myTemplate.txt");Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt");

Validation:JSR-303

public class PersonForm {        @NotNull        @Size(max=64)        private String name;        @Min(0)        private int age;}

SpEL

//解析器ExpressionParser parser = new SpelExpressionParser();Expression exp = parser.parseExpression("'Hello World'.concat('!')");String message = (String) exp.getValue();//Hello World!//表达式获取属性@Value("#{ systemProperties['user.region'] }")private String defaultLocale;