spring知识点

一、获取spring容器

1、Spring中,管理XML配置Bean定义的容器:ApplicationContext context = new ClassPathXmlApplicationContext("application.xml")。通过容器可以获取bean,context .getBean("beanId")。

2、Spring中,管理注解Bean定义的容器有两个:AnnotationConfigApplicationContext和AnnotationConfigWebApplicationContex。这两个类是专门处理Spring注解方式配置的容器,直
接依赖于注解作为容器配置信息来源的IOC容器。AnnotationConfigWebApplicationContext是AnnotationConfigApplicationContext的web版本,两者的用法以及对注解的处理方式几乎。

 

二、bean配置与管理

2.1、spring xml配置文件:配置bean

<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="duke" class="com.springinaction.springidol.Juggler" > 
        <!-- 通过构造方法设置属性值 -->
        <constructor-arg value="15"></constructor-arg>
    </bean>

</beans>

2.2、从Spring3.0,@Configuration用于定义配置类。配置bean相当于一个spring xml配置文件

package com.dxz.demo.configuration;

import org.springframework.context.annotation.Configuration;

@Configuration
public class TestConfiguration {

@Bean
public Juggler duke() { return new com.springinaction.springidol.Juggler(); } }

 

三、自定义注解

import java.lang.annotation.*;

@Documented
@Inherited
@Target({ ElementType.FIELD, ElementType.METHOD ,ElementType.TYPE_USE,ElementType.ANNOTATION_TYPE,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RedisHandel {
     String key() default "";
     String keyField() default "username";
}

 

四、获取自定义注解

4.1、获取指定注解所有的 Bean

Map<String,Object> objectMap = applicationContext.getBeansWithAnnotation(Service.class);

4.2、获取指定注解所有的 Bean 的名字

String[] beanNames = applicationContext.getBeanNamesForAnnotation(Service.class);

 

posted @ 2019-04-27 23:36  N神3  阅读(231)  评论(0编辑  收藏  举报