• Spring的注解开发-Spring配置类的开发


    Bean配置类的注解开发

    • @Component等注解替代了标签,但像等非标签怎样去使用注解去替代呢?定义一个配置类替代原有的xml配置文件,标签以外的标签,一般都是在配置类上使用注解完成的
    • @Configuration注解标识的类为配置类,替代原有的xml配置文件,该注解的第一个作用是标识该类是一个配置类,第二个作用是具备@Component注解的作用,将该配置类交给Spring容器管理
    • @ComponentScan组件扫描配置,替代原有的xml文件中的
      • base-package的配置方式
      • 指定一个或者多个包名:扫描指定包及其子包下使用的注解类
      • 不配置包名:扫描当前@ComponentScan注解配置类所在包及其子包的类
    • @PropertySource注解用于加载外部properties资源配置,替代原有xml文件中的 配置
    • @Import用于加载其它配置类,替代原有xml中的配置
    • 具体示例代码如下
        1. package com.example.Configure;
        2. import com.example.Beans.otherBeans;
        3. import org.springframework.context.annotation.ComponentScan;
        4. import org.springframework.context.annotation.Configuration;
        5. import org.springframework.context.annotation.Import;
        6. import org.springframework.context.annotation.PropertySource;
        7. @Configuration // todo 标注当前类是一个配置类(替代配置文件)、其中包含@Compoent注解
        8. //
        9. @ComponentScan({"com.example"})
        10. //
        11. @PropertySource("jdbc.properties")
        12. //
        13. @Import(otherBeans.class)
        14. public class SpringConfig {
        15. }

    小结

    • 创建配置类作用其实就是用来替代配置文件的作用,xml配置文件中的不同标签都在配置类中用对应的注解进行替代,由此获取Spring容器的方式也会发生变化,由之前的xml方式获取Spring核心容器变为通过注解的方式加载Spring容器的核心配置类。
        1. package com.example.Test;
        2. import com.example.Configure.SpringConfig;
        3. import org.springframework.context.ApplicationContext;
        4. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
        5. public class TestApplicationContext {
        6. public static void main(String[] args) {
        7. // xml方式加载Spring容器的核心配置文件
        8. // ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        9. // 注解方式加载Spring容器的核心配置类
        10. ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        11. System.out.println(context.getBean("dataSource"));
        12. }
        13. }

  • 相关阅读:
    YOLO 系列论文精读 & YOLOv4
    【后端】python2和python3的语法差异
    python Matplotlib Tkinter-->tab切换3
    基于EditPlus的PL0语言功能扩充
    JavaScript:实现ExponentialSearch指数搜索算法(附完整源码)
    【网页设计】web前端期末大作业html+css
    软件测试工程师怎么样面试上好的公司?
    后厂村路灯:【干货分享】AppleDevelop苹果开发者到期重置
    【Happy!1024】C++智能指针
    RAG的进化之路:从单兵作战到多智协作
  • 原文地址:https://blog.csdn.net/weixin_64939936/article/details/133465458