public class Classroom { private MathTeacher teacher; public Classroom(){ teacher = new MathTeacher(); } public void education(){ teacher.speak(); } }
public class Classroom { private Teacher teacher; public Classroom(Teacher t){ teacher = t; } public void education(){ teacher.speak(); } }
@Test public void ClassroomTest(){ MathTeacher mathTeacher = new MathTeacher(); Classroom mathCr = new Classroom(mathTeacher); mathCr.education(); PhysicalTeacher physicalTeacher = new PhysicalTeacher(); Classroom pCr = new Classroom(physicalTeacher); pCr.education(); }
@Test public void findUser(Integer id) { Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; try { /*噩梦一般的sql拼接*/ String sql = "select * from user where id="+id; connection = getConn(); statement = connection.prepareStatement(sql); resultSet = statement.executeQuery(); User user = null;/*写到手残的列取值*/ while (resultSet.next()) { user = new User(); user.setId(resultSet.getInt("id")); user.setName(resultSet.getString("name")); user.setSex(resultSet.getString("sex")); } } catch (SQLException e) { e.printStackTrace(); }finally{/*收尾工作*/ if (null!=resultSet) { try { resultSet.close(); } catch (SQLException e) {e.printStackTrace();} } if (null!=statement) { try { statement.close(); } catch (SQLException e) {e.printStackTrace();} } if (null!=connection) { try { connection.close(); } catch (SQLException e) {e.printStackTrace();} } } }
容器有两种
Spring自带了多种应用上下文实现,下列是最常用到的。
<!-- 声明一个简单的Bean --> <bean id="mT" class="com.test.coupling.MathTeacher" /> <!-- 通过构造器依赖注入① --> <bean id="cr_1" class="com.test.coupling.Classroom"> <constructor-arg ref="mT" /> </bean> <!-- 通过构造器依赖注入② --> <bean id="cr_2" class="com.test.coupling.Classroom"> <constructor-arg value="30"/> <constructor-arg ref="mT" /> </bean> <!-- 调用属性setter方法设置属性值 --> <bean id="cr_3" class="com.test.coupling.Classroom"> <property name="number" value="30" /> <property name="teacher" ref="mT"/> </bean> <!-- 内部Bean:缺点不能复用,影响XML可读性。 --> <bean id="cr_4" class="com.test.coupling.Classroom"> <property name="number" value="30" /> <property name="teacher"> <bean class="com.test.coupling.MathTeacher" /> </property> </bean> <!-- 设置空值 :潜在用法是覆盖自动装配的值--> <bean id="cr_5" class="com.test.coupling.Classroom"> <property name="teacher" ><null /></property> </bean> <!-- 指定初始化/销毁方法 --> <bean id="mT" class="com.test.coupling.MathTeacher" init-method="initMt" destroy-method="destroyMt"/> <!-- 设置Bean的作用域 --> <bean id="cr_4" class="com.test.coupling.Classroom" scope="prototype"/> <!-- 通过自定义方法创建Bean:通过这种方式来实现一个Bean的单例(在整个应用中) --> <bean id="cr_3" class="com.test.coupling.Classroom" factory-method="getInstance"/>
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd" default-init-method="init" default-destroy-method="destroy" > </beans>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="mT" class="com.test.coupling.MathTeacher" /> <bean id="cr" class="com.test.coupling.Classroom" p:number="30" p:teacher-ref="mT" /> </beans>
Spring提供的集合配置元素
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="mT" class="com.test.coupling.MathTeacher" /> <bean id="eqC" class="com.test.coupling.Computer" /> <bean id="cr" class="com.test.coupling.Classroom" > <property name="seatNames"> <list> <value>座位_1</value> <value>座位_2</value> <value>座位_3</value> </list> </property> <property name="teachers"> <list> <ref bean="mT"/> <bean class="com.test.coupling.PhysicalTeacher"/> </list> </property> <property name="students"> <set> <bean class="com.test.coupling.Students"/> <bean class="com.test.coupling.Students"/> </set> </property> <property name="equipment"> <map> <entry key="bb" value="blackboard"/> <entry key="c" value-ref="eqC"/> </map> </property> <property name="slogan"> <props> <prop key="s1">好好学习天天向上</prop> </props> </property> </bean> </beans>
SpEl表达式
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd "> <bean id="sr" class="com.test.wwq.impl.RoleImpl" > <property name="name" value="学生"/> </bean> <util:list id="roles"> <bean class="com.test.wwq.impl.RoleImpl" p:name="学生"/> <bean class="com.test.wwq.impl.RoleImpl" p:name="老师"/> <bean class="com.test.wwq.impl.RoleImpl" p:name="校长"/> </util:list> <util:map> <entry key="club_1" value="篮球社"/> <entry key="club_2" value="足球社"/> </util:map> <util:properties id="provinces" location="classpath:" /> <bean id="" class="com.test.coupling.Students" > <!-- 字面值:字符串,数字,浮点,科学计数法,布尔 --> <property name="name" value="#{'李连杰'}" /> <!-- 与非SpEl表达式混用 --> <property name="nativePlace" value="河北省_#{石家庄}" /> <!-- 引用Bean --> <property name="role" value="#{sr}" /> <!-- 引用Bean的属性/方法结果 --> <property name="roleName" value="#{sr.name}" /> <property name="behavior" value="#{sr.behavior()}" /> <!-- 操作Bean的属性/方法结果 --> <property name="capitalBehavior" value="#{sr.behavior().toUpperCase()}" /> <!-- 使用null-safe存取器避免NullPointerException --> <property name="lowercaseBehavior" value="#{sr.behavior()?.toLowerCase()}" /> <!-- 操作类:T()运算符调用类作用域的方法和常量 --> <property name="pi" value="#{T(java.lang.Math).PI}" /> <property name="number" value="NUM_#{T(java.lang.Math).random()}" /> <!-- 访问List集合成员 --> <property name="role" value="#{roles[0]}" /> <!-- 访问Map集合成员 --> <property name="club" value="#{roles['club_2']}" /> <!-- 访问Properties --> <property name="provinces" value="#{provinces['0100']}" /> <!-- systemEnvironment:机器环境变量 --> <property name="homePath" value="#{systemEnvironment['HOME']}" /> <!-- systemProperties:启动时设置的所有属性(-D参数)--> <property name="homePath" value="#{systemEnvironment['application.home']}" /> <!-- 得到字符串摸个字符 --> <property name="group" value="#{'A,B,C,D'[0]}"/> <!-- 查询集合 --> <property name="role" value="#{roles.?[name eq '学生']}"/> <!-- 投影集合:从集合的每个成员选择特定的属性放入一个新的集合(可以多个属性进行计算) --> <property name="roleNames" value="#{roles.![name]}"/> </bean> </beans>
<!-- 指定Bean的自动装配方式 --> <bean id="user" class="com.wwq.test.User" autowire="byName"></bean> <!-- 自动装配和显示装配混合使用 --> <bean id="user" class="com.wwq.test.User" autowire="byName"> <property name="" /><null/></property> </bean> <!-- 取消byType匹配资格 --> <bean id="user" class="com.wwq.test.User" primary="false"></bean>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd" default-autowire="byType"> </beans>
<context:annotation-config>
示例1
设置Bean的@Qualifier
@Qualifier("studentsUserDao") public class StudentsUserDao implements UserDao{ }
注入ID为userDao的Bean
@Autowired @Qualifier("studentsUserDao") private UserDao userDao;
示例2
创建自定义的限定器
@Target({ElementType.FIELD,ElementType.PARAMETER,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Qualifier public @interface StudentsUserDaoInStrument{ }使用自定义的限定器
@StudentsUserDaoInStrument public class StudentsUserDao implements UserDao{ }
public class StuService{ @Autowired @StudentsUserDaoInStrument private UserDao userDao; ...... }
public class StuService{ private UserDao userDao; public StuService(Provider<UserDao> userDaoProvider){ userDao = userDaoProvider.get(); } }
<context:component-scan base-package="com.test.wwq"></context:component-scan>
示例
@Component(value="stu") public class StudentsUserDao{ }
public class StuService{ @Autowired @Qualifier("stu") private UserDao userDao; ...... }
示例1:
<context:component-scan base-package="com.wwq.test"> <context:include-filter type="assignable" expression="com.wwq.test.UserDao"/> </context:component-scan>示例2
<context:component-scan base-package="com.wwq.test"> <context:include-filter type="assignable" expression="com.wwq.test.UserDao"/> <context:exclude-filter type="annotation" expression="com.wwq.test.FailureRole"/> </context:component-scan>
示例
@Configuration public class SpringConfig { @Bean public UserDao userDao(){ return new UserDao(); } @Bean public UserDao stuService(){ return StuService(userDao()); } }
在方法执行时触发 犯法所属的类型 使用任意参数 ____|____ ________|________ __|__ | | | | | | execution( * com.test.wwq.User.registered(..)) |___| |__________________________| | | 返回任意类型 特定方法
执行user.registered()方法 ______________________|__________________________ | | execution( * com.test.wwq.User.registered(..)) && within(com.test.wwq.*) |___||_____________________| | | 与(and)操作符 当com.test.wwq包下的任意类的方法被调用时
<bean id="log" class="com.test.wwq.LogUtil"/> <aop:config> <aop:aspect ref="log"> <aop:pointcut id="logPointcut" expression="切点表达式"/> <aop:before pointcut-ref="logPointcut" method="通知方法" /> <aop:after-returning pointcut-ref="logPointcut" method="通知方法" /> <aop:after-throwing pointecut="切点表达式" method="通知方法" /> </aop:aspect> </aop:config>
public void watchPerformance(ProceedingJoinPoint joinpoint){ try{ /*执行被通知方法之前*/ joinpoint.proceed(); /*执行被通知方法之后*/ }catch(){ /*执行被通知方法异常*/ } }
<aop:config> <aop:aspect ref="log"> <aop:pointcut id="logPointcut" expression="切点表达式"/> <aop:around pointcut-ref="logPointcut" method="watchPerformance()" /> </aop:aspect> </aop:config>
<aop:config> <aop:aspect ref="log"> <aop:pointcut id="logPointcut" expression="切点表达式"/> <aop:before pointcut-ref="logPointcut" method="通知方法" arg-names="形参名称"/> </aop:aspect> </aop:config>
<aop:config> <aop:aspect> <aop:declare-parents types-matching="com.test.wwq.User+" implement-interface="com.test.wwq.Role" default-impl="com.test.wwq.impl.RoleImpl"/> </aop:aspect> </aop:config>
@Aspect public class ContestantIntroducer{ @DeclareParents(value="com.test.wwq.User+",defaultImpl = GraciousContestant.class) public static Contestant contestant; }