• Spring学习笔记注解式开发(3)


    一、Bean的注解式开发

    1.1、注解开发的基本和@Component

    Spring除了xml配置文件进行配置之外,还可以使用注解方式进行配置,注解方式慢慢成为xml配置的替代方案。我们有了xml开发的经验,学习注解开发就方便了许多,注解开发更加快捷方便。

    • Spring提供的注解有三个版本:
      • 2.0时代,Spring开始出现注解
      • 2.5时代,Spring的Bean配置可以使用注解完成
      • 3.0时代,Spring其他配置也可以使用注解完成,我们进入全注解时代

    基本Bean注解,主要是使用注解的方式替代原有xml标签及其标签属性的配置

    <bean id="" name="" class="" scope="" lazy-init="" init-method="" destroy-method=""abstract="" autowire="" factory-bean="" factory-method="">bean>
    
    • 1

    使用@Component注解替代标签

    xml配置注解描述
    @Component被该注解表示的类,会在指定扫描范围内被Spring加载并实例化
    //
    @Component("userDao")
    public class UserDaoImpl implements UserDao{
        @Override
        public void show() {
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    
    <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
           http://www.springframework.org/schema/context/spring-context.xsd">
    
        
        
        <context:component-scan base-package="com.huanglei"/>
    beans> 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    public class test1 {
        @Test
        public void ComponentTest(){
            ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("beans.xml");
            Object bean = classPathXmlApplicationContext.getBean("userDao");
            System.out.println(bean);
        }
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    1.2 注解式开发

    如果@Component不设置name属性,那会回自动将首字母小写的类名转化成name,在访问的时候就用其首字母小写的类名进行访问

    • 相关属性用注解开发替代的标签
    xml配置注解描述
    @Scope在类上或使用了@Bean标注的方法上,标注Bean的作用范围,取值为singleton或prototype
    @Lazy在类上或使用了@Bean标注的方法上,标注Bean是否延迟加载,取值为true和false
    @PostConstruct在方法上使用,标注Bean的实例化后执行的方法
    @PreDestroy在方法上使用,标注Bean的销毁前执行方法

    8.3、@Component的三个衍生注解

    由于JavaEE开发是分层的,为了每层Bean标识的注解语义化更加明确,可以乱写,但是为了让注解语义化明确,建议按照标准书写

    • @Component又衍生出如下三个注解:
    @Component衍生注解描述
    @Repository在Dao层类上使用
    @Service在Service层类上使用
    @Controller在Web层类上使用
    //service层
    @Service("userService")
    public class UserServiceImpl implements UserService{}
    //dao层
    @Repository("userDao")
    public class UserDaoImpl implements UserDao{}
    //web层
    @Controller("userService")
    public class UserController{} 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    二、Bean依赖注入注解开发

    2.1、依赖注入相关注解

    Bean依赖注入的注解,主要是使用注解的方式替代xml的标签完成属性的注入操作

    <bean id=" "class="">
    	<property name="" value=""/>
    	<property name="" ref=""/>
    bean> 
    
    • 1
    • 2
    • 3
    • 4
    • Spring主要提供如下注解,用于在Bean内部进行属性注入的:
    属性注入注解描述
    @Value使用在字段或方法上,用于注入普通数据
    @Autowired使用在字段或方法上,用于根据类型(byType)注入引用数据
    @Qualifier使用在字段或方法上,结合@Autowired,根据名称注入
    @Resource使用在字段或方法上,根据类型或名称进行注入
    • @Value一般会引用Spring容器里面的一些值,根据key进行获取
    • @Autowired根据类型进行注入,如果同一类型的Bean有多个,尝试根据书写的名字进行二次匹配,如果匹配不成功则会报错
    • 配合使用@Qualifier注解,可以在同一类型的多个Bean中根据名称注入相应的Bean
    • @Resource不指定名称参数时,根据类型注入,指定名称则根据名称注入
    @Service("userService")
    public class UserServiceImpl implements UserService{
    
        @Value("zhangsan")
        private String username;
        
        //@Autowired,如果同一类型的Bean有多个,尝试根据名字进行二次匹配,如果匹配不成功则会报错
        //@Qualifier("userDao2"),配合使用@Autowired注解,可以在同一类型的多个Bean中根据名称注入相应的Bean
        
        @Resource 
        private UserDao userDao;
        @Override
        public void show() {
            System.out.println(username);
            System.out.println(userDao);
        }
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    2.2、@Autowired扩展

    @Autowired使用该注解时,所查看的是参数的类型,跟方法的名称无关

    @Service("userService")
    public class UserServiceImpl implements UserService{
        @Autowired 
        public void xxx(UserDao userDao) {
            System.out.println("xxx:"+userDao);
        }
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    该注解同样可以获取一个集合,可以将同一类型的多个Bean打印出来

    @Service("userService")
    public class UserServiceImpl implements UserService{
        @Autowired 
        public void yyy(List<UserDao> userDaoList) {
            System.out.println("yyy:"+userDaoList);
        }
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    三、非自定义Bean注解开发

    非自定义Bean不能像自定义Bean一样使用@Component进行管理,非自定义Bean要通过工厂的方式进行实例化,使用@Bean标注方法即可,@Bean的属性为beanName,如不指定为当前工厂方法名称

    //将方法返回值Bean实例以@Bean注解指定的名称存储到spring容器中
    @Bean ("datasource")
    public DataSource dataSource (){
    	DruidDataSource dataSource = new DruidDataSource();
    	dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    	dataSource.setUrl("jdbc:mysql://localhost:3306/itheima");
    	dataSource.setUsername("root");
    	dataSource.setPassword("123456");
    	return dataSource;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    @Bean标注后面不加name值,则将类名赋值为name属性值

    • 在参数中注入
    @Component
    public class otherBean {
        @Bean("dataSource")
        public DataSource dataSource(
       		@Value("${jdbc.driver}") String driver
       		@Qualifier("userDao") UserDao UserDao//不需要写@Autowired
    	){
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName(driver);
            dataSource.setUrl("jdbc:mysql://localhost:3306/mybatis");
            dataSource.setUsername("root");
            dataSource.setPassword("123456");
            return dataSource;
        }
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    四、Bean配置类的注解开发

    @component -->
    @Configuration --> 表示上面配置的文件
    下面是其他的标签注解开发展示:

    	
    	<context:component-scan base-package="com.huanglei"/>
    	
    	<context:properties-placeholder location="classpath:jdbc.properties"/>
    	
    	<import resource="classpath:beans.xml"/>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    在用注解式开发的时候需要在配置类上加 @Configuration
    作用:

    1. 表明这是一个配置类
    2. 使其就具备@Component的功能
    xml配置注解描述
    @ComponentScan组件扫描配置
    @PropertySource获取到properties文件里的信息
    @Import导入其他的xml配置文件

    base-package的配置方法:

    • 可以配置一个或者多个包:扫描的为该包及其子包下使用注解的类
    • 不配置包名:扫描当前@componentScan注解配置类所在包及其子包下的类
    @Component
    @Configuration
    @ComponentScan(backages={"com.huanglei","com.itheima"})
    @PropertySource({"classpath:jdbc.properties"})
    //
    @Import(otherBean.class)
    public class SpringConfig {}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    其他的注解式开发:

    @Primary 这个是来调节同类型Bean优先顺序的,就是说在利用ByTybe调用bean对象的时候有多个对象,如果没有@primary,那么就按照之前的调用规则进行调用,如果存在@Primary那么就有限调用这个Bean对象

    @Repository("userDao")
    public class UserDaoImpl implements UserDao{}
    @Repository("userDao2")
    @Primary
    public class UserDaoImpl2 implements UserDao{} 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    @Bean("dataSource")
    public DataSource dataSource(){}
    
    @Bean("dataSource2")
    @Primary //如果没添加这个,那么在调用的时候,就会按照名字调用上面那个Bean对象
    public DataSource dataSource2(){} 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    扩展:@Profile注解的作用同于xml配置时学习profile属性,是进行环境切换使用的

    <beans profile="test">
    
    • 1

    注解@Profile标注在类或方法上,标注当前产生的Bean从属于哪个环境,只有激活了当前环境,被标注的Bean才能被注册到Spring容器里,不指定环境的Bean,任何环境下都能注册到Spring容器里

    @Repository("userDao")
    @Profile("test") //表面实在test环境下面
    public class UserDaoImpl implements UserDao{}
    @Repository("userDao2")
    public class UserDaoImpl2 implements UserDao{} 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 可以使用以下两种方式指定被激活的环境:
      • 使用命令行动态参数,虚拟机参数位置加载 -Dspring.profiles.active=test
      • 使用代码的方式设置环境白能量System.setProperty("profiles.active","test");
    @Test
    public void test2(){
        System.setProperty("spring.profiles.active","test");
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
        Object userDao = annotationConfigApplicationContext.getBean("userDao");
        System.out.println(userDao);
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    五、Spring注解的解析原理

    在这里插入图片描述
    结论:只要将Bean对应的BeanDefinition注册到beanDefinitionMap中,就可以经历整个SpringBean的生命周期,最终实例化进入单例池中

    使用@Component等注解配置完毕后,要配置组件扫描才能使注解生效

    六、Spring注解式开发第三方框架

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis2"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
    <!--配置SqlSessionFactoryBean,作用将SqlSessionFactory存储到spring容器-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--MapperScannerConfigurer,作用扫描指定的包,产生Mapper对象存储到Spring容器-->
    <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.Smulll.mapper"></property>
    </bean> 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    使用注解方式:
    注解方式,Spring整合MyBatis的原理,关键在于**@MapperScan**,@MapperScan不是Spring提供的注解,是MyBatis为了整合Spring,在整合包org.mybatis.spring.annotation中提供的注解,源码如下:

    package com.huanglei.listener;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.w3c.dom.css.CSSPrimitiveValue;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    
    public class ContextLoaderListener implements ServletContextListener {
        private String CONTEXT_LOCATION = "configLocation";
        @Override
        public void contextInitialized(ServletContextEvent sec) {
            //获取到全局变量configLocation
            ServletContext servletContext = sec.getServletContext();
            String contextLocation = servletContext.getInitParameter(CONTEXT_LOCATION);
            contextLocation = contextLocation.substring("classpath:".length());
            //首先创建Spring容器
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext(contextLocation);
            //将Spring容器放到ServletContext域当中
            servletContext.setAttribute("applicationContext",applicationContext);
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent servletContextEvent) {
    
        }
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    重点关注一下@lmport({MapperScannerRegistrar.class),当@MapperScan被扫描加载时,会解析@Import注解,从而加载指定的类,此处就是加载了MapperScannerRegistrar

  • 相关阅读:
    UDP的MTU发现
    中睿天下&Coremail | 2023年Q3企业邮箱安全态势观察报告
    SpringBoot 实战 开发中 16 条最佳实践
    开发中,遇到后端返回的数据列表不更新怎么办?
    Java运算符的使用
    深入理解Java CompletableFuture并发编程模型
    软件工程第七周
    Python 中的 4 个非常好用的自动化脚本
    PY32F003F18之通用定时器MspInit函数
    求和、计数的窗口函数应用
  • 原文地址:https://blog.csdn.net/gua_Piter/article/details/133938276