1.首先,我们先了解一下,Spring是什么?
Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson创建。简单来说,Spring是一个分层的JavaSE/EEfull-stack(一站式) 轻量级开源框架。Spring致力于J2EE应用的各层的解决方案,而不是仅仅专注于某一层的方案。Spring是企业应用开发的“一站式”选择,并贯穿表现层、业务层及持久层。Spring可以应用到每一个层面上。
在我认为,Spring最核心的 是一个 IOC(控制反转) 和 AOP 容器框架(面向切面编程)。【最核心的两个作用】
2.Spring的优点有哪些?
1.使用Spring的IOC容器,将对象之间的依赖关系交给Spring,降低组件之间的耦合性,让我们更专注于应用逻辑
2.可以提供众多服务,事务管理,WS等。
3.AOP的很好支持,方便面向切面编程。
4.对主流的框架提供了很好的集成支持,如Hibernate,Struts2,JPA等
5.Spring DI机制降低了业务对象替换的复杂性。
6.Spring属于低侵入,代码污染极低。
7.Spring的高度可开放性,并不强制依赖于Spring,开发者可以自由选择Spring部分或全部
3.Spring配置环境需要的jar包(并没有跟struts和hibernate相关联)
4.Spring的xml配置
//依赖注入
<bean id="user" class="com.hp.bean.User">
<property name="name" value="AQA"></property>
<property name="age" value="11"></property>
<property name="list">
<list>
<value>宝马</value>
<value>蓝兔</value>
</list>
</property>
<property name="map">
<map>
<entry>
<key>
<value>小米</value>
</key>
<value>不要钱</value>
</entry>
<entry>
<key>
<value>苹果</value>
</key>
<value>1块钱</value>
</entry>
</map>
</property>
</bean>
有问题啊 这软件 添加代码块 总自己跳到最上面 没办法, 只能把代码考过来了
//构造器注入
<bean id="person" class="com.itheima12.spring.di.xml.constructor.Person">
<!--
constructor-arg指的是构造器中的参数
index 角标 从0开始
value 如果一般类型,用value赋值
ref 引用类型赋值
-->
<constructor-arg index="0" value="asdfsafd"></constructor-arg>
<constructor-arg index="1" ref="student"></constructor-arg>
</bean>
AOP通知介绍
环绕通知、后置通知的配置
<bean id="service" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interfaces">
<value>com.hp.service.Service</value>
</property>
<property name="interceptorNames">
<list>
<value>Mymethod</value>
<value>afterhanlder</value>
</list>
</property>
<property name="target" ref="serviceimpl"></property>
</bean>
<bean id="serviceimpl" class="com.hp.service.impl.Serviceimpl"></bean>
<bean id="Mymethod" class="com.hp.handler.MyHandler"></bean>
<bean id="afterhanlder" class="com.hp.handler.AfterHandler"></bean>
action类
环绕通知
public class MyHandler implements MethodInterceptor {
public Object invoke(MethodInvocation method) throws Throwable {
System.out.println("环绕(拦截)通知加载完成");
Object object = method.proceed();
System.out.println("通知加载完成");
return object;
}
}
后置通知
public class AfterHandler implements AfterReturningAdvice {
public void afterReturning(Object arg0, Method method, Object[] arg2, Object arg3) throws Throwable {
System.out.println("后置通知加载完成");
}
AOP的配置使用
<bean id="mylog" class="com.hp.handler.MyLog"></bean>
<bean id="service" class="com.hp.service.impl.Serviceimpl"></bean>
<aop:config>
<aop:aspect id="advice" ref="mylog">
//切点位置
<aop:pointcut expression="execution(* com.hp.service.impl.Serviceimpl.*(..))" id="pointcut"/>
<aop:before method="write" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
action类的引入
@Aspect
public class MyLog {
@Pointcut("execution(* com.hp.service.impl.Serviceimpl.*(..))")
public void write() {
System.out.println("圣诞节快了哦!每个人都要平平安安的!");
}
}
配置成功后,切点位置会有转向的小箭头哦!
好了,这样就完成了Spring的配置