Spring纯注解开发上篇(包含Component、Configuration、ComponentScan、Scope、PostConstruct、PreDestroy注解)
文章目录
- 💨更多相关知识👇
 - 
- Spring纯注解开发
 - 
- (1)@Component注解开发定义bean(在IOC容器创建对象)
 - 
- ⭐代码演示
 
 - (2)@Component注解的三个衍生注解
 - 
- ⭐代码演示
 
 - (3)@Configuration纯注解开发和@ComponentScan注解使用
 - 
- 🌟配置文件到纯注解开发演变图
 - ⭐代码演示
 
 - (4)bean的作用范围
 - 
- ⭐singleton代码演示
 - ⭐prototype代码演示
 
 - (5)bean的生命周期
 - 
- ⭐代码演示
 
 
 
 - 作者:KJ.JK
 
💨更多相关知识👇
💖Spring中的创建对象的三种方式、第三方资源配置管理详细描述及使用(XML版完结篇)
💖Spring中的bean的配置、作用范围、生命周期详细描述及使用(XML版上篇)
💖Spring中的依赖注入、setter与构造器注入、自动装配与集合注入详细描述及使用(XML版中篇)
💖异常处理与解决方案详解上篇
💖异常处理与解决方案详解下篇
💖Math类与System类的常用方法使用
💖JavaEE中的静态方法定义、方法重载要求、return作用详解
💖List接口的常用方法,精华总结
💖JavaEE中的Stream流的常用方法
💖JavaEE中的Stream流知识点使用,精华总结,一文直接上手
🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈 🌈
🍂个人博客首页: KJ.JK
欢迎大家点赞👍收藏💖评论💬关注🔒
💖源码获取 | 💻学习交流 | 🤝商务合作 | 💨私信作者
💨推荐一款实用的模拟面试、刷题练习算法的神器、适用于所有的程序猿👉点击开始免费刷题,跟着博主走上巅峰💪
Spring纯注解开发
(1)@Component注解开发定义bean(在IOC容器创建对象)
              "注解开发定义bean顺序:"
                  
                  1.在所有需要放到容器中的类,在类上使用@Component注解
                  
                    @Component("bookDao")     
                    public class BookDaoImpl implements BookDao {
                      
                    }
                    @Component   //如果没有指定id,则使用类名首字母小写做为id,即:bookServiceImpl
                    public class BookServiceImpl implements BookService {
                         
                    }
                      2.核心配置文件中通过基包扫描加载bean   "(会扫描这个包和它所有的子包)"
                          
                         <context:component-scan base-package="com.itheima"/>
/*
  注意:
       @Component("bookDao") // 配置了Component注解的类,IoC容器就会创建该类的对象,并放到容器中, id名字叫bookDao 
       
       @Component // 如果没有指定id,自动取id名字: 类名首字母变小写 如: (BookServiceImpl -> id:bookServiceImpl)
*/
⭐代码演示
// BookDaoImpl类
@Component("bookDao") // 配置了Component注解的类,IoC容器就会创建该类的对象,并放到容器中, id名字叫bookDao
public class BookDaoImpl implements BookDao {
    public void save() {
        System.out.println("book dao save ..." );
    }
}
------------------------------------------------------------------------------------------------------------
//BookServiceImpl类
@Component// 没有指定id,自动取id名字: 类名首字母变小写(bookServiceImpl)
public class BookServiceImpl implements BookService {
    private BookDao bookDao;
    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }
    public void save() {
        System.out.println("book service save ...");
    }
}
------------------------------------------------------------------------------------------------------------
//xml类
<?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">
    <!--组件扫描: 去指定包中和子包中找带有
           @Component 的类并创建对象放到容器中
        base-package: 基包, 指定要查找包和子包-->
    <context:component-scan base-package="com.itheima"/>
</beans>
------------------------------------------------------------------------------------------------------------
//测试类
public class AnnotationTest {
    @Test
    public void test01() {
        // 1.加载类路径下的配置文件
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 2.使用名称获取bean
        BookDao bookDao =   (BookDao) context.getBean("bookDao");
        bookDao.save();
        BookService bookService = (BookService) context.getBean("bookServiceImpl");
        bookService.save();
        // 3.关闭容器
        context.close();
    }
}

(2)@Component注解的三个衍生注解
                    * @Controller:用于"表现层bean定义"    //Controller注解不能使用其它的注解代替
                    
                    * @Service: 用于"业务层bean定义"         "(service类)"
                    
                    * @Repository: 用于"数据层bean定义"      " (Dao层注解,接口类)"
⭐代码演示

(3)@Configuration纯注解开发和@ComponentScan注解使用
                 * Spring3.0开启了"纯注解开发模式",使用"Java类替代配置文件",开启了Spring快速开发赛道
                 
                 * Java类代替Spring核心配置文件
                 
                     
                 * "@Configuration注解" : "用于设定当前类为配置类"     
                                 //(有这个注解的并且@ComponentScan配置了扫描的路径就会被带上车)
                        //Spring在启动的时候会自动扫描并加载所有配置类,然后将配置 类中bean放入容器
                     
                 * "@ComponentScan注解" : "用于设定基包扫描路径",此注解只能添加一次,"多个数据请用数组格式{}"
                                      //扫描包或子包中类里面和Spring相关的注解
                              //针对标注了@Controller、@Service、@Repository、@Component 的类都可以别spring扫描到
                 
                    如: @ComponentScan({"com.itheima.service","com.itheima.dao"})
                       //相当于扫描到带有注解的带它上车
                   
                 * 读取Spring核心配置文件初始化容器对象切换为"读取Java配置类初始化容器对象"
                     
                                                                    //加载配置文件初始化容器    
               ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
                                                                   //加载配置类初始化容器
               ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
                     
------------------------------------------------------------------------------------------------------------
    
         "纯注解开发顺序"
                      1.用一个Java类来写"@Configuration注解" (设定当前类为配置类,代替Spring的配置类文件)
                                  "@ComponentScan注解" (设定基包扫描路径)
    
                      2.读取Java配置类初始化容器对象
             ApplicationContext ctx = new AnnotationConfigApplicationContext("java配置类.class");
🌟配置文件到纯注解开发演变图

⭐代码演示
//java类代替配置文件
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
@Configuration // Spring的配置类, 相当于applicationContext.xml
@ComponentScan({"com.itheima.dao", "com.itheima.service", "com.itheima.util"}) // 相当于基包扫描
public class SpringConfig {
}
------------------------------------------------------------------------------------------------------------
//测试类
    @Test
    public void test01() {
        // 1.加载配置类
         AnnotationConfigApplicationContext context =
                 new AnnotationConfigApplicationContext(SpringConfig.class);
        // 2.获取bean
        BookDao bookDao1 = (BookDao) context.getBean("bookDao");
        bookDao1.save();
        BookService bookService  = (BookService) context.getBean("bookServiceImpl");
        bookService.save();
        // 3.关闭容器
         context.close();
    }

(4)bean的作用范围
                          * 使用"@Scope"注解定义bean作用范围
                               
                          * 范例
                              
                              @Component
                              @Scope("singleton")
                              public class BookDaoImpl {
                                  
                              }
/*
   singleton : 单例
   prototype : 多例
*/
⭐singleton代码演示
//作用范围类
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
// @Component("bookDao") // 指定id为bookDao
@Repository("bookDao")
 @Scope("singleton") // singleton: 单例    prototype: 多例
public class BookDaoImpl implements BookDao {
    public void save() {
        System.out.println("book dao save ..." );
    }
}
------------------------------------------------------------------------------------------------------------
//测试类
    @Test
    public void test01() {
        // 1.加载配置类
         AnnotationConfigApplicationContext context =
                 new AnnotationConfigApplicationContext(SpringConfig.class);
        // 2.获取bean
        BookDao bookDao1 = (BookDao) context.getBean("bookDao");
        BookDao bookDao2 = (BookDao) context.getBean("bookDao");
        bookDao1.save();
        System.out.println("同一个对象: " + (bookDao1 == bookDao2));
        BookService bookService = (BookService) context.getBean("bookServiceImpl");
        bookService.save();
        // 3.关闭容器
         context.close();
    }    

⭐prototype代码演示
//作用范围类
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
// @Component("bookDao") // 指定id为bookDao
@Repository("bookDao")
 @Scope("prototype") // singleton: 单例    prototype: 多例
public class BookDaoImpl implements BookDao {
    public void save() {
        System.out.println("book dao save ..." );
    }
}
------------------------------------------------------------------------------------------------------------
//测试类
    @Test
    public void test01() {
        // 1.加载配置类
         AnnotationConfigApplicationContext context =
                 new AnnotationConfigApplicationContext(SpringConfig.class);
        // 2.获取bean
        BookDao bookDao1 = (BookDao) context.getBean("bookDao");
        BookDao bookDao2 = (BookDao) context.getBean("bookDao");
        bookDao1.save();
        System.out.println("同一个对象: " + (bookDao1 == bookDao2));
        BookService bookService = (BookService) context.getBean("bookServiceImpl");
        bookService.save();
        // 3.关闭容器
         context.close();
    }    

(5)bean的生命周期
                 * 使用 "@PostConstruct"、"@PreDestroy" 定义bean生命周期
                     
                 * 这两个注解不是Spring框架提供的,由JDK提供的,但"JDK9.0以后去掉了",所以高版本使用要在pom.xml导包
                     
                             <dependency>
                                  <groupId>javax.annotation</groupId>
                                  <artifactId>javax.annotation-api</artifactId>
                                  <version>1.3.2</version>
                             </dependency>
                     
                 * "@PostConstruct": 初始化方法, 在"构造器后执行"
                     
                 * "@PreDestroy" : 销毁方法, 在"对象销毁前执行"   //对多例模式无效
⭐代码演示
//生命周期类
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
// @Component("bookDao") // 指定id为bookDao
@Repository("bookDao")
 @Scope("singleton") // singleton: 单例    prototype: 多例
public class BookDaoImpl implements BookDao {
    public void save() {
        System.out.println("book dao save ..." );
    }
    // 初始化方法, 在构造器后执行
     @PostConstruct      //bean初始化容器注解
    public void init() {
        System.out.println("BookDaoImpl 初始化完毕!");
    }
    // 销毁方法, 在对象销毁前执行
     @PreDestroy        //bean销毁容器注解
    public void destroy() {
        System.out.println("BookDaoImpl 销毁了!");
    }
}
------------------------------------------------------------------------------------------------------------
//测试类
 @Test
    public void test01() {
        // 1.加载配置类
         AnnotationConfigApplicationContext context =
                 new AnnotationConfigApplicationContext(SpringConfig.class);
        // 2.获取bean
        BookDao bookDao1 = (BookDao) context.getBean("bookDao");
        BookDao bookDao2 = (BookDao) context.getBean("bookDao");
        bookDao1.save();
        System.out.println("同一个对象: " + (bookDao1 == bookDao2));
        BookService bookService = (BookService) context.getBean("bookServiceImpl");
        bookService.save();
        // 3.关闭容器
         context.close();
    }

作者:KJ.JK
文章对你有所帮助的话,欢迎给个赞或者 star,你的支持是对作者最大的鼓励,不足之处可以在评论区多多指正,交流学习
 
                    版权声明:程序员胖胖胖虎阿 发表于 2022年9月11日 上午1:32。
转载请注明:Spring纯注解开发上篇(包含Component、Configuration、ComponentScan、Scope、PostConstruct、PreDestroy注解) | 胖虎的工具箱-编程导航
                    
            转载请注明:Spring纯注解开发上篇(包含Component、Configuration、ComponentScan、Scope、PostConstruct、PreDestroy注解) | 胖虎的工具箱-编程导航
相关文章
暂无评论...
