Spring学习
Spring
通过class全类名的bean注入,必须有一个无参的构造器,如果写了一个有参的就不行
通过ID来引用bean
ApplicationContext是IOC容器,Spring提供了两种:BeanFactory(常见的实现类:XmlBeanFactory)和ApplicationContext,前者是底层的。它的主要实现类:
ClassPathXmlApplicationContext FileSystemXmlApplicationContext
ConfigurableApplicationContext扩展于ApplicationContext,新增了两个方法refresh()和close()
getBean是在BeanFactory中定义的,也可以用类来获取(可能不唯一,id是唯一的)
Spring三种注入:属性注入(property)、构造方法注入(constructor)、接口注入
<bean id= class=> <constructor-arg vlaue= index="0"> <constructor-arg vlaue= index="1"> //方法有重载的话,加上type ="java.lang.String" //上面也可以加上value的子节点,并赋值 //如果包含转义字符,值用![CDATA[值]]来表示 属性注入: <bean id="textEditor" class="com.tutorialspoint.TextEditor"> <property name="spellChecker" ref="spellChecker"/> </bean>
引用Bean,用ref,也可以定义内部bean:
//内部bean <property name="car"> <bean class=""> <constructor-arg value=""> //值为null值的写法 <constructor-arg><null/></constructor-arg> //写法 <bean id="outerBean" class="..."> <property name="target"> <bean id="innerBean" class="..."/> </property> </bean>
级联赋值
property name=car.maxSpeed value=250 //注意:属性需要先初始化才可以级联赋值,否则异常
集合属性
写法 <property name="addressList"> <list> <ref bean="address1"/> <ref bean="address2"/> <value>Pakistan</value> </list> </property> <!-- Passing bean reference for java.util.Set --> <property name="addressSet"> <set> <ref bean="address1"/> <ref bean="address2"/> <value>Pakistan</value> </set> </property> <!-- Passing bean reference for java.util.Map --> <property name="addressMap"> <map> <entry key="one" value="INDIA"/> <entry key ="two" value-ref="address1"/> <entry key ="three" value-ref="address2"/> </map> </property> </bean>
p命名空间为属性赋值(在属性较多的时候)
bean id class p:age= p:name= p:car-ref= <bean id="john-classic" class="com.example.Person" p:name="John Doe" p:spouse-ref="jane"/> </bean>
自动装配
autowire属性指定自动装配的模式:(默认是按照byType)
byType:根据类型自动装配(注意类型不唯一的冲突)
byName:根据ID名字自动装配
constructor:较少用
<bean id="textEditor" class="com.tutorialspoint.TextEditor" autowire="byName"> <property name="name" value="Generic Text Editor" /> </bean> constructor少写了一个参数 它尝试把它的构造函数的参数与配置文件 beans名称中的一个进行匹配和连线 类似于byTpye <bean id="textEditor" class="com.tutorialspoint.TextEditor" autowire="constructor"> <constructor-arg value="Generic Text Editor"/> </bean>
配置文件的继承
bean id class p:city= p:street= abstruct=”true”
bean id p:property= parent=”id”
继承抽象父类id,继承多个用逗号隔开
依赖
bean id class depend-on=”id”
被依赖的没定义则出错
IOC中bean的实例默认是单例的,prototype每次都会产生新的实例,
bean id class scope=”prototype”
使用外部配置文件
1. 写一个properties 加入context命名空间 <context:property-placeholder location="classpath:db.properties"
SpEL spring的EL表达式
//单引号和双引号都能界定字符串 #{5} #{22.5} #{1e3} #{'1'} #{"1"} #{T(java.lang.Math).PI*80} 引用静态属 #{car.price>30000? 'a':'b'}
bean的生命周期
创建bean实例--》为bean赋值--》bean的初始化方法--》使用--》销毁方法 后置处理器(继承BeanPostProcessor,在配置继承类中不用写ID) beforeinit afterinit 可以在处理方法中修改对象并返回,可以配置多个,通过实现Ordered接口实现顺序 初始化回调:继承InitializingBean 或者在xml中注明init-method 销毁回调:destroy-method 也可以在beans的标签中,写上default-init-method和default-destroy-method 顺序: 1.BeforeInitialization 2.init 3.AfterInitialization 4.destroy
工厂方法配置bean
1. 通过静态工厂方法来配置bean,注意不是配置静态工厂方法实例(类里面的实例) bean id clas=".factory.StaticCarFactory" factory-method="getCar" <constructor-arg value="audi"> 该bean返回的是Car 2. 非静态(实例)工厂方法 先配置工厂实例: clas id class= 通过工厂实例来配置bean bean id factroy-bean=指向工厂实例的id bean factory-method=工厂方法名 <constructor-arg value>
通过FactoryBean来配置bean
继承Factory<T> 复写getObject(),getObjectType() isSingleton() bean id class=指向继承Factory的类 property name value 返回的实例是通过getObject()返回的
基于注解的配置_1
1.组件扫描,侦测注解 Component:基本注解,标识了一个受spring管理的组件 Respository:标识持久层组件,后面可以括号跟名字(ID) Service:标识服务层组件 Controller:标识表现层组件 对于扫描到的组件,Spring有默认的命名策略:使用非限定类名,第一个字母小写。也可以在注解中通过value属性值标识组件的名称 在组件类上使用了特定额注解后,还要在Spring的配置文件中声明: <context:component-scan base-package=基包(其他包逗号隔开) resource-pattern="autowire/*.class"> <context:include-filter>子节点标识要包含的目标类 <context:exclude-filter>子节点标识要排除在外的目标类 scan下可以拥有多个filer子节点 例子: <context:component-scan base-package='' use-default-filters='false'> <context:include-filter type='annotation' expression='类名' //includ指定包含哪些组件,需要和use-default-filters使用,false表明用下面的filter <context:component-scan>元素还会自动注册AutowireAnnotationBeanPostProcessor实例,该实例可以装配具有@Autowired和@Resource、@Inject注解的属性: Autowired:构造器、普通字段、一切具有参数的方法都可以应用(包括数组、集合、Map上) (required=false):表示在容器中没配置也可以 如果有多个类型匹配(多个接口的子类),按照名字匹配
基于注解的配置_2
@Required:注解应用于bean属性的setter方法,bean属性配置时必须放在xml配置文件中 @Autowired: @Qualifier:指定确切的bean @Autowired @Qualifier("student1") private Student student;
AOP(基于注解)
类上加注解@Aspect @Before("execution(publi int com....add(int, int))") beforeMethod(JoinPoint joinPoint)//joinPoint.getSignature().getName() add改成*则会在所有的方法上起作用 其他方法: After AfterRunning AfterThrowing Around 配置: 配置文件中加入AOP的命名空间 切面bean加入IOC <aop:aspectj-autoproxy></aop:aspectj-autoproxy>//自动生成代理对象 afterThrowing(JoinPoint joinPoint, NullPointExcepiton ex)//匹配异常并实现后序处理 aroundMehtod(ProceedingJoinPoint)//里面的参数决定是否执行目标方法;有返回值,即方法的返回值 方法注解@order(1)指定优先级,越小优先级越高 定义一个方法,用于声明切入点表达,不用写实现 @Pointcut("execution(public int com....*())") public void declareJointPointExpression(){} 然后引用:@Before("declareJointPointExpression()")(包外要注明包名,类外要注明类)
基于配置文件
<aop:config> //配置切点表达式 <aop:pointcut expression="ececution()" //配置切面即通知 <aop:aspect ref="切面类" order="1"> <aop:before method:"beforeMethod"/>
Spring对JDBC的支持
建立数据源db.properties并导入: <context:property-placeholder location="classpath:db.properties"/> 配置C3p0 <bean id="dataSource" class=""> <property name="" value="> 配置Spring的JdbcTemplate <bean id class="JdbcTemplate"> <property name="dataSource"> jdbcTemplate.update(sql,"jack",4)
Spring事务管理
声明式事务管理 TransactionManager:核心类 配置事务管理器: <bean id class=org...DataSourceTransactionManager> <property name=dataSource ref=dataSource> 启用事务注解 <tx:annotation-driven transaction-manager=transactionManager/> 对用的事务方法上要加上@Transactional注解 事物的传递,默认是propagation,被另一个事务调用时,会使用另一个事务 @Transactional(propagation=Propagation.REQUIRED) 新开一个事务:Propagation.REQUIRED_NEW 事务的隔离级别:isolation=Isolation.READ_COMMITTED 回滚异常(默认对运行时异常回滚):rollbackFory以及noRllbackFor(不会滚的异常) 只读:readOnly=false,timeout=3)(超时回滚) 事务于xml配置文件的方式: bean id class=服务类 配置事务管理器 bean id class=Manager类 配置事务属性: <tx:advice id transaction-manager tx:attributes tx:methos name=方法名 propagation= tx:method name=方法名 配置事务切入点: <aop:config> aop:pointcut expression=服务类 id=txPointCut aop:advisor advice-ref=txadvice pointcut-ref=txPointCut
Spirng在web中的使用
需要额外的jar包:spring-web和spring-webmvc 在web应用被服务器加载时就创建IOC容器: ServletContextListener#contextInitialized(ServletContextEvent scd)方法中创建IOC容器 然后把其放在ServletContext域中 Spring配置文件的名字可以配置到WEB应用初始化参数中(web.xml) 配置: <context-param> param-name contextConfigLocation param-value classpath:applicationContext.xml <listener> <listener-class>org.springframework.web.context.ContextLoaderListener Spring整合Struts2 在Strut中配置的Spring的Action的class指向Spring中的该类的ID 整合原理:会从IOC容器中获取Action实例 Struts2的action是非单例的,在配置action的bean时,要加上scope="prototype"选项