SpringBean生命周期,动态代理 SpringBean生命周期 动态代理 CglibDynamicProxy JDKDynamicProxy SpringBean生命周期 流程
代码 package cn. yx. zg. lifecyclebean ; import org. springframework. beans. BeansException ; import org. springframework. beans. factory. * ; import org. springframework. beans. factory. annotation. Autowired ; import org. springframework. beans. factory. config. BeanFactoryPostProcessor ; import org. springframework. beans. factory. config. BeanPostProcessor ; import org. springframework. beans. factory. config. ConfigurableListableBeanFactory ; import org. springframework. context. ApplicationContext ; import org. springframework. context. ApplicationContextAware ; import org. springframework. stereotype. Component ; import javax. annotation. PostConstruct ; import javax. annotation. PreDestroy ; @Component public class CompleteLifecycleBean implements BeanNameAware , BeanFactoryAware , ApplicationContextAware , InitializingBean , DisposableBean { private String beanName; private BeanFactory beanFactory; private ApplicationContext applicationContext; private DatabaseConnection databaseConnection; // =============== 1. 实例化阶段 =============== public CompleteLifecycleBean ( ) { System . out. println ( "=== 1. 构造方法执行 ===" ) ; System . out. println ( " 创建 CompleteLifecycleBean 实例" ) ; System . out. println ( " 此时依赖还未注入,databaseConnection = " + databaseConnection) ; } // =============== 2. 依赖注入阶段 =============== @Autowired public void setDatabaseConnection ( DatabaseConnection databaseConnection) { System . out. println ( "=== 2. 依赖注入 ===" ) ; System . out. println ( " 注入 DatabaseConnection" ) ; this . databaseConnection= databaseConnection; System . out. println ( " databaseConnection = " + databaseConnection) ; } // =============== 3. Aware 接口回调 =============== @Override public void setBeanName ( String name) { this . beanName= name; System . out. println ( "=== 3.1 BeanNameAware ===" ) ; System . out. println ( " Bean 名称: " + name) ; } @Override public void setBeanFactory ( BeanFactory beanFactory) throws BeansException { this . beanFactory= beanFactory; System . out. println ( "=== 3.2 BeanFactoryAware ===" ) ; System . out. println ( " BeanFactory 已注入" ) ; } @Override public void setApplicationContext ( ApplicationContext applicationContext) throws BeansException { this . applicationContext= applicationContext; System . out. println ( "=== 3.3 ApplicationContextAware ===" ) ; System . out. println ( " ApplicationContext 已注入" ) ; } // =============== 4/6. BeanPostProcessor 前后置处理 =============== // 在 CustomBeanPostProcessor 中实现 // =============== 5. 初始化方法 =============== @PostConstruct public void postConstructMethod ( ) { System . out. println ( "=== 5.1 @PostConstruct ===" ) ; System . out. println ( " 执行 @PostConstruct 方法" ) ; System . out. println ( " 验证依赖是否注入: " + ( databaseConnection!= null ) ) ; initializeConnection ( ) ; } @Override public void afterPropertiesSet ( ) throws Exception { System . out. println ( "=== 5.2 InitializingBean ===" ) ; System . out. println ( " 执行 afterPropertiesSet()" ) ; validateConfiguration ( ) ; } // 通过 @Bean 或 XML 配置的 init-method public void customInitMethod ( ) { System . out. println ( "=== 5.3 自定义 init-method ===" ) ; System . out. println ( " 执行自定义初始化方法" ) ; loadInitialData ( ) ; } // =============== 7. Bean 就绪使用 =============== public void processRequest ( ) { System . out. println ( "=== 7. Bean 执行业务逻辑 ===" ) ; if ( databaseConnection== null ) { throw new IllegalStateException ( "数据库连接未初始化" ) ; } System . out. println ( " 处理业务请求" ) ; databaseConnection. executeQuery ( "SELECT * FROM users" ) ; } // =============== 8. 销毁方法 =============== @PreDestroy public void preDestroyMethod ( ) { System . out. println ( "=== 8.1 @PreDestroy ===" ) ; System . out. println ( " 执行 @PreDestroy 方法" ) ; releaseExternalResources ( ) ; } @Override public void destroy ( ) throws Exception { System . out. println ( "=== 8.2 DisposableBean ===" ) ; System . out. println ( " 执行 destroy() 方法" ) ; if ( databaseConnection!= null ) { databaseConnection. close ( ) ; } } // 通过 @Bean 或 XML 配置的 destroy-method public void customDestroyMethod ( ) { System . out. println ( "=== 8.3 自定义 destroy-method ===" ) ; System . out. println ( " 执行自定义销毁方法" ) ; System . out. println ( " Bean 销毁完成" ) ; } // =============== 私有辅助方法 =============== private void initializeConnection ( ) { System . out. println ( " 初始化数据库连接..." ) ; // 初始化逻辑 } private void validateConfiguration ( ) { System . out. println ( " 验证配置..." ) ; // 验证逻辑 } private void loadInitialData ( ) { System . out. println ( " 加载初始数据..." ) ; // 数据加载逻辑 } private void releaseExternalResources ( ) { System . out. println ( " 释放外部资源..." ) ; // 资源释放逻辑 } @Override public String toString ( ) { return "CompleteLifecycleBean{" + "beanName='" + beanName+ '\'' + ", databaseConnection=" + databaseConnection+ '}' ; } } // 依赖的 Bean @Component class DatabaseConnection { public void executeQuery ( String sql) { System . out. println ( "执行 SQL: " + sql) ; } public void close ( ) { System . out. println ( "关闭数据库连接" ) ; } } @Component class CustomBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization ( Object bean, String beanName) throws BeansException { if ( beaninstanceof CompleteLifecycleBean ) { System . out. println ( "=== 4. BeanPostProcessor 前置处理 ===" ) ; System . out. println ( " 处理 Bean: " + beanName) ; System . out. println ( " 可以修改 Bean 属性或返回包装对象" ) ; // 示例:修改 Bean 属性 CompleteLifecycleBean lifecycleBean= ( CompleteLifecycleBean ) bean; System . out. println ( " 当前状态: " + lifecycleBean) ; // 可以在这里进行一些前置检查 System . out. println ( " 前置处理完成" ) ; } return bean; } @Override public Object postProcessAfterInitialization ( Object bean, String beanName) throws BeansException { if ( beaninstanceof CompleteLifecycleBean ) { System . out. println ( "=== 6. BeanPostProcessor 后置处理 ===" ) ; System . out. println ( " 处理 Bean: " + beanName) ; System . out. println ( " Bean 初始化完成,可以进行包装" ) ; // 示例:创建代理对象(AOP 通常在这里实现) System . out. println ( " 可以返回代理对象增强功能" ) ; System . out. println ( " 后置处理完成" ) ; // 返回原始 Bean 或代理 Bean // return Proxy.newProxyInstance(...); } return bean; } } @Component class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor { @Override public void postProcessBeanFactory ( ConfigurableListableBeanFactory beanFactory) { System . out. println ( "BeanFactoryPostProcessor 执行" ) ; // 在 Bean 实例化之前修改 Bean 定义 } } 动态代理 CglibDynamicProxy package cn. yx. zg. proxy ; import net. sf. cglib. proxy. Enhancer ; import net. sf. cglib. proxy. MethodInterceptor ; import net. sf. cglib. proxy. MethodProxy ; import java. lang. reflect. Method ; // 目标类(不需要实现接口) class ProductService { public void addProduct ( String name) { System . out. println ( "添加产品: " + name) ; } public void addProduct ( String name, Integer age) { System . out. println ( "添加产品: " + name+ "年龄" + age) ; } public String getProduct ( int id) { System . out. println ( "查询产品ID: " + id) ; return "Product" + id; } } // CGLIB方法拦截器 class MyMethodInterceptor implements MethodInterceptor { @Override public Object intercept ( Object obj, Method method, Object [ ] args, MethodProxy proxy) throws Throwable { System . out. println ( "CGLIB代理前处理 - 方法名: " + method. getName ( ) ) ; Object result= proxy. invokeSuper ( obj, args) ; System . out. println ( "CGLIB代理后处理" ) ; return result; } } public class CglibDynamicProxy { public static void main ( String [ ] args) { // 创建增强器 Enhancer enhancer= new Enhancer ( ) ; // 设置父类 enhancer. setSuperclass ( ProductService . class ) ; // 设置回调函数 enhancer. setCallback ( new MyMethodInterceptor ( ) ) ; // 创建代理对象 ProductService proxy= ( ProductService ) enhancer. create ( ) ; // 通过代理对象调用方法 proxy. addProduct ( "手机" , 2 ) ; proxy. addProduct ( "手机" ) ; System . out. println ( proxy. getProduct ( 1 ) ) ; } } JDKDynamicProxy package cn. yx. zg. proxy ; import java. lang. reflect. InvocationHandler ; import java. lang. reflect. Method ; import java. lang. reflect. Proxy ; // 接口定义 interface UserService { void addUser ( String name) ; String getUser ( int id) ; void addUser2 ( String name, Integer age) ; } // 目标对象实现 class UserServiceImpl implements UserService { @Override public void addUser ( String name) { System . out. println ( "添加用户: " + name) ; } @Override public String getUser ( int id) { System . out. println ( "查询用户ID: " + id) ; return "User" + id; } @Override public void addUser2 ( String name, Integer age) { System . out. println ( "添加用户2: " + name+ ", age: " + age) ; } } // JDK动态代理处理器 class MyInvocationHandler implements InvocationHandler { private Object target; public MyInvocationHandler ( Object target) { this . target= target; } @Override public Object invoke ( Object proxy, Method method, Object [ ] args) throws Throwable { System . out. println ( "JDK代理前处理 - 方法名: " + method. getName ( ) ) ; Object result= method. invoke ( target, args) ; System . out. println ( "JDK代理后处理" ) ; return result; } } public class JDKDynamicProxy { public static void main ( String [ ] args) { // 创建目标对象 UserService userService= new UserServiceImpl ( ) ; // 创建代理对象 UserService proxy= ( UserService ) Proxy . newProxyInstance ( userService. getClass ( ) . getClassLoader ( ) , userService. getClass ( ) . getInterfaces ( ) , new MyInvocationHandler ( userService) ) ; // 通过代理对象调用方法 proxy. addUser2 ( "张三" , 20 ) ; proxy. addUser ( "张三" ) ; System . out. println ( proxy. getUser ( 1 ) ) ; } }