![这里写图片描述](https://img-blog.csdn.net/20171022103235785?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZ3d0MDQyNQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
ApplicationContext
依赖的包
- org.springframework.beans
- org.springframework.context
ApplicationContext
这个是提供接口的核心,它还有个直接子接口WebApplicationContext
![这里写图片描述](https://img-blog.csdn.net/20171020163320533?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZ3d0MDQyNQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
可以直接使用的实现类有:ClassPathXmlApplicationContext 或者FileSystemXmlApplicationContext
下图是原理图:
![这里写图片描述](https://img-blog.csdn.net/20171020163600219?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZ3d0MDQyNQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
初始化一个容器并配置
//使用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");
PetStoreService service = context.getBean("petStore", PetStoreService.class);
List<String> userList = service.getUsernameList();
Bean定义的依赖
![这里写图片描述](https://img-blog.csdn.net/20171020164858713?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZ3d0MDQyNQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
<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:
jdbc.username=sa
jdbc.password=root
作用域
![这里写图片描述](https://img-blog.csdn.net/20171020165853721?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZ3d0MDQyNQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
@SessionScope
@RequestScope
@ApplicationScope
@Scope
注解配置
<?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的过滤器
![这里写图片描述](https://img-blog.csdn.net/20171020181701795?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZ3d0MDQyNQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
@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);
}
}
<beans>
<context:property-placeholder location="classpath:/com/acme/jdbc.properties"/>
</beans>
jdbc.properties
jdbc.url=jdbc:hsqldb:hsql:
jdbc.username=sa
jdbc.password=
@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;
}
}
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;
}
}
}
public class BlackListNotifier implements ApplicationListener<BlackListEvent> {
private String notificationAddress;
public void setNotificationAddress(String notificationAddress) {
this.notificationAddress = notificationAddress;
}
@EventListener(condition = "#blEvent.test == 'foo'")
@Async
@Order(42)
public void processBlackListEvent(BlackListEvent event) {
}
}
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();
@Value("#{ systemProperties['user.region'] }")
private String defaultLocale;