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;
### Spring IOC 原理及实现 #### 1. 控制反转(IOC)的概念 控制反转(Inversion of Control,简称 IOC)是一种设计思想,旨在将对象的创建和管理从应用程序代码中分离出来。通过 IOC,开发者无需手动管理对象的生命周期和依赖关系,而是由框架负责这些任务。这种思想使得开发者可以专注于业务逻辑的实现,而不需要关心对象之间的交互细节[^1]。 #### 2. 依赖注入(DI) 依赖注入(Dependency Injection,简称 DI)是实现 IOC 的一种方式。DI 的核心在于通过外部配置或注解的方式,将对象的依赖关系注入到目标对象中,而不是由对象自己负责依赖的创建和管理。依赖注入有三种主要形式:构造器注入、Setter 方法注入和字段注入[^4]。 #### 3. Spring IOC 容器的核心接口 Spring 框架提供了两种主要的 IOC 容器接口: - **BeanFactory**:这是 Spring 框架的基础接口,面向 Spring 内部使用。它负责配置、创建和管理 Bean 的生命周期。 - **ApplicationContext**:这是一个更高级的容器接口,面向开发者使用。它扩展了 BeanFactory 的功能,提供了更多的企业级特性,如国际化支持、事件传播等。在实际开发中,通常使用 ApplicationContext 而非 BeanFactory[^2]。 #### 4. Spring IOC 的实现方式 Spring IOC 的实现主要包括以下几个方面: ##### (1) 元数据解析 Spring 使用 XML 文件、Java 注解或 Java 配置类来定义 Bean 的元数据。例如,通过 `<bean>` 标签在 XML 文件中定义 Bean,或者使用 `@Component`、`@Service` 等注解在 Java 类上声明 Bean[^5]。 示例代码(XML 配置): ```xml <bean id="userDao" class="com.mayuanfei.springioc.dao.impl.UserDaoImpl" /> ``` 示例代码(注解配置): ```java @Component public class UserDaoImpl implements UserDao { // 实现方法 } ``` ##### (2) 依赖注入 Spring 通过反射机制解析 Bean 的依赖关系,并将其注入到目标对象中。以下是一个简单的依赖注入示例: 示例代码(字段注入): ```java @Service public class UserService { @Autowired private UserDao userDao; // 自动注入 UserDao } ``` ##### (3) 生命周期管理 Spring 容器会管理 Bean 的整个生命周期,包括初始化、运行时和销毁阶段。开发者可以通过实现特定的接口(如 `InitializingBean` 和 `DisposableBean`)或使用注解(如 `@PostConstruct` 和 `@PreDestroy`)来定制 Bean 的生命周期行为。 示例代码(生命周期管理): ```java @Component public class MyBean { @PostConstruct public void init() { System.out.println("Bean 初始化"); } @PreDestroy public void destroy() { System.out.println("Bean 销毁"); } } ``` ##### (4) 扩展机制 Spring 提供了丰富的扩展点,允许开发者自定义容器的行为。例如,通过实现 `BeanFactoryPostProcessor` 或 `BeanPostProcessor` 接口,可以在 Bean 初始化前后插入自定义逻辑[^4]。 #### 5. Spring IOC 的优势 Spring IOC 的核心优势包括: - **解耦**:对象之间不再直接依赖具体实现,而是通过接口或抽象类进行交互。 - **灵活性**:通过配置文件或注解动态管理 Bean,便于修改和扩展。 - **可维护性**:集中处理对象的创建和依赖关系,降低了代码复杂度。 ### 总结 Spring IOC 是一种通过容器管理对象生命周期和依赖关系的设计模式。其核心原理包括元数据解析、依赖注入、生命周期管理和扩展机制。通过这些机制,Spring 实现了对象控制权的反转,从而提高了系统的解耦性、灵活性和可维护性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值