浅析Spring bean创建生命周期

本文展示了如何在Spring Boot项目中配置依赖,创建程序入口,定义关键Bean,以及使用AOP进行方法拦截。内容包括:设置Spring Boot启动配置,定义UserService并实现事务管理,创建OrderService和GoodsInfo Bean,以及配置数据源和AOP切面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、开局两张图仅做笔记用

 

 

二、代码有注释回头方便自己复习

1、简单的依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2、程序入口

package com.example.demo.api;

import com.example.demo.DemoApplication;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class IOCTest {
    public static void main(String[] args) throws Exception {
        // DemoApplication 建springboot项目送的启动文件
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(DemoApplication.class);
        UserService userService = (UserService) annotationConfigApplicationContext.getBean("userService");
        userService.seyHi();

//        if (userService instanceof InitializingBean){
//            ((InitializingBean) userService).afterPropertiesSet();
//        }

    }
}

3、主要的一个bean

package com.example.demo.service;

import com.example.demo.entity.UserInfo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;

@Component
public class UserService implements InitializingBean {
    @Autowired
    OrderService orderService;
    @Autowired
    JdbcTemplate jdbcTemplate;
//    UserInfo admin;

    /**
     * 初始化 前执行的方法
     */
    @PostConstruct
    public void setMyorderservice() {
        //TODO admin查库
    }

    /**
     * 初始化 后执行的方法
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        //TODO 或者在这里admin查库
    }

    /**
     * 被代理的方法
     */
    @Transactional
    public void seyHi() {
        System.out.println("你好!!!");
        jdbcTemplate.execute("insert user_tb value (1,2,3,4,5,6,,7,8)");
        testTransactional(); //直接调用会导致后边的事务失效:意味着不同对象执行testTransactional
//        userService.testTransactional();
    }

//    @Autowired
//    UserService userService;

    @Transactional(propagation = Propagation.NEVER)
    public void testTransactional() {

    }
}

4、次要的两个bean

package com.example.demo.service;

import com.example.demo.entity.GoodsInfo;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class OrderService {
    GoodsInfo goodsInfo;
    @Bean
    public GoodsInfo goodsInfo1(){
        return new GoodsInfo(null);
    }
    public OrderService(GoodsInfo goodsInfo) {
        this.goodsInfo = goodsInfo;
        System.out.println("goodsInfo = " + goodsInfo);
    }
}

package com.example.demo.entity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class GoodsInfo {
//    public GoodsInfo() {
//        System.out.println("goodsInfo 无参构造函数初始化");
//    }

    /**
     * 1、有无参构造函数直接使用无参构造函数其他有参直接被忽略掉即便是@Autowired指定也无效
     * 2、没有无无参构造函数且只有一个有参构造函数则默认唯一的这个有参构造
     * 3、没有无参构造函数且有多个有参构造函数就要@Autowire指定
     * @param gooodsName  当容器中只有一个Goodsreq bean的时候 gooodsName参数名可以谁便写,
     *                     当容器中有多个Goodsreq bean的时候 gooodsName参数名必须为goodsreq才能完成type和name的强匹配
     */
    @Autowired
    public GoodsInfo(Goodsreq gooodsName) {
        System.out.println("goodsInfo 无参构造函数初始化");
    }

    public GoodsInfo(String gooodsID,String month) {
        System.out.println("goodsInfo 有参构造函数初始化");
    }
}

5、贴上数据库bean和aop的bean

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * Configuration 能保证JdbcTemplate和 PlatformTransactionManager调用的dataSource bean为同一个
 * Component 等注解无法保证容器里的bean为同一个
 */
@Configuration
public class MysqlDB {
    @Bean
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource());
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource());
        return transactionManager;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setUrl("jdbc:mysql//127.0.0.1:3306/mydb");
        driverManagerDataSource.setUsername("root");
        driverManagerDataSource.setPassword("AQS123qwe.");
        return driverManagerDataSource;
    }
}
package com.example.demo.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class SeyAOP {
    @Before("execution(public void com.example.demo.service.UserService.seyHi())")
    public void beforeAOP(JoinPoint joinPoint){
        System.out.println("切点逻辑"+joinPoint.toString());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值