Sping框架的理解

mac2026-05-16  7

Spring框架的理解

一、Spring框架解决的主要问题

1.1创建对象

控制权从调用的类转换到spring容器,由spring来实例化对象

1.2依赖注入

依赖注入,通过在构建bean对象的时候,把数据加入到对象中,所谓的依赖的意思就是这里的数据有可能是通过其它的bean对象得到的。

二、 IOC

2.1IOC的概念

Ioc—Inversion of Control,即“控制反转”,不是什么技术,而是一种设计思想。在Java开发中,Ioc意味着将你设计好的对象交给容器控制,而不是传统的在你的对象内部直接控制。

2.2配置方式

2.2.1属性配置

value 注入基本数据类型 ref 注入已有的bean

<!-- 把所有的类都生成bean对象,scope默认作用域是共享模式(prototype为非共享模式,生成的对象的地址不一样 )--> <bean id="boy" class="com.jinglin.model.Boy"> <!-- 属性注入值 --> <property name="name" value="zhangsan"></property> <!-- 关联到另外一个bean对象 --> <property name="girlfriend" ref="girl"></property> <!-- 集合属性注入 --> <property name="habbies"> <!--注入的list的集合值 --> <list> <value>网球</value> <value>乒乓球</value> <value>网游</value> </list> </property> <!-- 键值对的集合的数据注入 --> <property name="subject"> <!-- 给map这种集合数据类型注入 --> <map> <entry> <!-- 表示键 --> <key><value>英语</value></key> <!-- 表示值 --> <value>98</value> </entry> <entry> <key><value>数学</value></key> <value>99</value> </entry> </map> </property> </bean> <bean id="girl" class="com.jinglin.model.Girl"> <!-- 属性注入值 --> <property name="name" value="lily"></property> <!-- 关联到另外一个bean对象 --> <property name="boyfriend" ref="boy"></property> </bean>

2.2.2实例化的方式

1.通过默认构造器实例化 通过serter方式将依赖注入 2.静态工厂方法实例化

<!--用静态工厂方法创建一个connection作为springbean--> <bean id="connection" factory-method="getConnection" class="com.woniuxy.spring.common.JDBCUtils"/> <!--某个类(JDBCUtils)的静态方法(getConnection),返回值作为bean-->

2.2.3工厂bean实例化

<!--工厂bean--> <bean id="holidayFactory" class="com.woniuxy.spring.factory.HolidayFactory"/> <!--holidayBean--> <bean id="holiday" factory-bean="holidayFactory" factory-method="create"></bean>

2.2.4spring的FactoryBean接口实例化

public class CarFactory implements FactoryBean<Car> { @Override public Car getObject() throws Exception { return new Car(); } @Override public Class<?> getObjectType() { return Car.class; } }

相关xml的配置

<bean id="car" class="com.woniuxy.spring.factory.CarFactory"/>

2.3依赖注入的几种方式

1.通过setter注入 2.构造器注入 3.注解注入 -注册springbean: @Controller 控制层 @Service service层 @Repository dao层 @Component 组件 -自动依赖注入: @AutoWired 标记属性 @Value 基本变量 -设置生命周期: @PostConstruct 初始化 @PreDestroy 销毁 -作用域范围 @Scope 原型 =>prototype=>每次创建一个实例 单例 =>singleton => 一个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: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 https://www.springframework.org/schema/context/spring-context.xsd"> <!--指定扫描的范围,包括递归的所有的包和子类--> <context:component-scan base-package="com.woniuxy.spring"/> </beans>

4.java配置式ioc 需要用到的注解:@Bean @Configuration@ComponentScan @Configuration 标记一个类为配置类 @Bean 标记某个方法返回值为Sping的bean 扫描

@Configuration 标记一个类为配置类 applicationContext.xml

@ComponentScan 打开包扫描功能,并且指定扫描的包 等价于 <context:component-scan base-package=“xxx”>

加入@Controller…@Autowired @PropertySource("{配置文件位置}")

@Configuration @ComponentScan("com.woniu.spring") @PropertySource("databaes.properties") public class AppConifgProperty { @Value("{$jdbc.driverClass}") private String driverClassName; @Value("{$jdbc.url}") private String url; @Value("{$jdbc.username}") private String username; @Value("{$jdbc.password}") private String password; @Bean public LoginMainUi loginMainUi(){ LoginMainUi loginMainUi = new LoginMainUi(); return loginMainUi; } @Bean public UserService userService(){ UserServiceImpl userService = new UserServiceImpl(); return userService; } @Bean public UserDAO userDAO(){ return new UserDAOImpl(); } @Bean public DruidDataSource druidDataSource(){ DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(driverClassName); druidDataSource.setUrl(url); druidDataSource.setUsername(username); druidDataSource.setPassword(password); return druidDataSource; } @Bean public QueryRunner queryRunner(){ return new QueryRunner(druidDataSource()); }

5.混合使用

在注解类上可以用@Import导入Java配置,用ImportResource导入xml配置 @Import(AppConfig.class) @ImportResource("applicationContext.xml")

2.4bean的生命周期和作用域

bean的作用域 默认单例 prototype 原型 => 每次创建一个实例[*]singleton 单例 => 一个bean的定义,只有一个实例,不是一个类只有一个实例request 一个请求一个实例session 一个会话一个实例websocket 一次websocket链接一个实例

beand 的生命周期 1.在bean配置上写init-method和destroy-method 2.实现InitializingBean和DisposableBean的接口并重写其方法

public class Cycle2 implements InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { System.out.println("开始...."); } @Override public void destroy() throws Exception { System.out.println("结束了...."); } }

2.5IOC的优势

-解耦合,类与类之间的耦合度降低 -提升代码的灵活性,可维护性

三、AOP

3.1AOP的概念

Aspect Oritened Proguramming 面向切面编程,把需要某一个系统功能的所有方法看做一个切面。

AOP的一些名词

连接点 JoinPoint 需要加入功能的位置,方法切入点 PointCut 真正执行加入功能的连接点通知 Advice 需要实现的功能切面 Aspect Java语言中,将切入点和通知等组装在一起的代码单元目标对象 Target 要操作的对象织入 Weave 将功能加入到切入点中的过程

应用场景:公共的,在很多的地方都会出现的功能;打印日志、性能监控、事务管理、安全验证, 每一个类的每一个public方法的参数都打印出来

3.2AOP的配置方式

1.将通知配置成一个java类+xml的配置方式 例如:

public class TransactionAdvice { public void begin(){ System.out.println("事务开启"); } public void commit(){ System.out.println("事务提交"); } public void rollback(){ System.out.println("事务回滚"); } } <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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="userService" class="com.woniuxy.spring.aop.service.impl.UserServiceImpl"/> <!--通知: 实现了打日志的功能--> <bean id="beforeExecution" class="com.woniuxy.spring.aop.component.BeforeExecution"/> <!--切入点:选出了需要增加功能的方法--> <bean id="pointCut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"> <property name="pattern" value="com.woniuxy.spring.aop.service.impl.UserServiceImpl.addUser"/> </bean> <!--切面:连接切入点和通知,让打日志功能在切入点的位置执行--> <bean id="aspect" class="org.springframework.aop.support.DefaultPointcutAdvisor"> <property name="pointcut" ref="pointCut"/> <property name="advice" ref="beforeExecution"/> </bean> <!--包装userService--> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/> </beans>

2.注解加java类式配置

@Component @Aspect public class TxConfig { @Pointcut("execution(* com.woniuxy.spring.aop.impl.*.*(..))") public void servicePoint(){ } @Around("servicePoint()") public Object point(ProceedingJoinPoint proceedingJoinPoint){ Object proceed =null; try { System.out.println("开启事务"); Object[] args = proceedingJoinPoint.getArgs(); proceed = proceedingJoinPoint.proceed(); System.out.println("提交事务"); } catch (Throwable throwable) { throwable.printStackTrace(); System.out.println("回滚事务"); } return proceed; } } <?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" 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.xsd"> <!--目标对象--> <bean id="userService" class="com.woniuxy.spring.aop.impl.UserServiceImpl"></bean> <bean id="productService" class="com.woniuxy.spring.aop.impl.ProductServiceImpl"></bean> <!--通知--> <bean id="txAdvice" class="com.woniuxy.spring.aop.component.TransationAntoAdvice"></bean> <!--切面配置--> <aop:config> <aop:aspect ref="txAdvice"> <!--切入点--> <aop:pointcut id="servicePoint" expression="execution(* com.woniuxy.spring.aop.impl.*.*(..))"/> <aop:around method="invoke" pointcut-ref="servicePoint"></aop:around> </aop:aspect> </aop:config> </beans>

3.纯注解式配置 在对应的类上加注解@Service(“userService”) 参数表示类的实例化对象

@Configuration @ComponentScan("com.woniuxy.spring.aop") @EnableAspectJAutoProxy public class TxAntoAdvice { }
最新回复(0)