Spring IOC

这里写图片描述

ApplicationContext

依赖的包

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

ApplicationContext

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

这里写图片描述

可以直接使用的实现类有:ClassPathXmlApplicationContext 或者FileSystemXmlApplicationContext
下图是原理图:

这里写图片描述

初始化一个容器并配置

//使用Xml
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

//使用Kotlin DSL
fun 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 instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);

// use configured instance
List<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.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.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注入

@Configuration
public 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.properties
jdbc.properties
jdbc.url=jdbc:hsqldb:hsql://localhost/xdb
jdbc.username=sa
jdbc.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;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值