Spring初阶_04注解的使用

基础代码演示

代码结构:
在这里插入图片描述
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">

    <!--
    @Repository  标记子啊数据访问层的类注册为Bean组件
    @Service  标记在业务路旁基层的类注册为Bean组件
    @Controller  标记在控制层的类注册为Bean组件
    @Component  标记非三层的普通的类注册为Bean组件
    
    不是非要每个层对应相应的注解;1、增强可读性
                               2、利于spring管理 排除扫描 <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    -->

<!--    <bean class="cn.songlinzi.controller.UserController" id="userController"></bean>-->
    <!--扫描包
    base-package 设置需要扫描的文件的路径
    排除扫描:<context:exclude-filter 设置需要排除扫描的选项
    包含扫描:<context:include-filter 设置需要包含扫描的选项
    type:1.annotation 默认 根据注解的完整限定名设置排除、包含
          2.assignable 根据类的完整限定名设置排除、包括
          3.aspect 根据切面表达式来设置排除、包括,使用较少
          4.regex 根据正则表达式来设置排除、包括,使用较少
          5.custom 根据接口来设置排除、包括,使用较少,此处时需要继承接口 org.springframework.core.type.TypeFilter
    use-default-filters 默认是true,会默认包含扫描@Repository @Service @Controller @Component
                             false,不会扫描@Repository @Service @Controller @Component ,所以在使用的时候就需要写上具体的部分,不然会全部排出,就会报错
    -->
    <context:component-scan base-package="cn.songlinzi" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>

当前各个类里面全部为空,下面为测试类

package cn.songlinzi.tests;

import cn.songlinzi.controller.UserController;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Author Joe
 * cn.songlinzi.tests
 * @Date 2021-11-28 19:13
 */
public class IocTest {
    @Test
    public void test01(){
        ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring_ioc.xml");
        UserController userController = ioc.getBean("userController", UserController.class);
        System.out.println(userController);
    }
}

User.java

package cn.songlinzi.beans;

import org.springframework.stereotype.Component;

@Component
public class User {
}

UserController.java

package cn.songlinzi.controller;

import org.springframework.stereotype.Controller;

@Controller
public class UserController {
}

UserDaoImpl.java

package cn.songlinzi.dao.impl;

import cn.songlinzi.dao.UserDao;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
}

UserDao.java

package cn.songlinzi.dao;

public interface UserDao {
}

UserServiceImpl.java

package cn.songlinzi.service.impl;

import cn.songlinzi.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
}

UserService.java

package cn.songlinzi.service;

/**
 * @Author Joe
 * cn.songlinzi.service
 * @Date 2021-11-28 19:10
 */
public interface UserService {
}

测试类

package cn.songlinzi.tests;

import cn.songlinzi.controller.UserController;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Author Joe
 * cn.songlinzi.tests
 * @Date 2021-11-28 19:13
 */
public class IocTest {
    @Test
    public void test01(){
        ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring_ioc.xml");
        UserController userController = ioc.getBean("userController", UserController.class);
        System.out.println(userController);
    }
}

小结:怎么使用注解将一个类注册为Bean的步骤

  1. 设置扫描包 context:component-scan
  2. 在对应的类名加上对应的注解
    使用上述的注解会自动将类名的首字母小写设置为Bean的名称

通过外部文件来获取对应的key值

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">

    <!--
    @Repository  标记子啊数据访问层的类注册为Bean主键
    @Service  标记在业务路旁基层的类注册为Bean主键
    @Controller  标记在控制层的类注册为Bean主键
    @Component  标记非三层的普通的类注册为Bean主键
    
    不是非要每个层对应相应的注解;1、增强可读性
                               2、利于spring管理 排除扫描 <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    -->

<!--    <bean class="cn.songlinzi.controller.UserController" id="userController"></bean>-->
    <!--扫描包
    base-package 设置需要扫描的文件的路径
    排除扫描:<context:exclude-filter 设置需要排除扫描的选项
    包含扫描:<context:include-filter 设置需要包含扫描的选项
    type:1.annotation 默认 根据注解的完整限定名设置排除、包含
          2.assignable 根据类的完整限定名设置排除、包括
          3.aspect 根据切面表达式来设置排除、包括,使用较少
          4.regex 根据正则表达式来设置排除、包括,使用较少
          5.custom 根据接口来设置排除、包括,使用较少,此处时需要继承接口 org.springframework.core.type.TypeFilter
    use-default-filters 默认是true,会默认包含扫描@Repository @Service @Controller @Component
                             false,不会扫描@Repository @Service @Controller @Component ,所以在使用的时候就需要写上具体的部分,不然会全部排出,就会报错
    -->
    <context:component-scan base-package="cn.songlinzi">
<!--        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
    </context:component-scan>
    <!--引用外部属性资源文件,可以通过@Value来获取里面的key值-->
    <context:property-placeholder location="db.properties"></context:property-placeholder>
</beans>

User.java

package cn.songlinzi.beans;

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

/**
 * @Author Joe
 * cn.songlinzi.beans
 * @Date 2021-11-28 19:24
 */
@Component
public class User {
    //使用@Value设置依赖注入的属性
    //除了可以写硬编码值,还可以使用${}、#{},
    // ${}是用于引入外部的值,比如properties的文件中的key会引入value值
    // #{} 是用于SpEL表达式的时候有用到
//    @Value("张三")
    @Value("${mysql.name}")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

测试类

    @Test
    public void test03(){
        User bean = ioc.getBean("user",User.class);
        System.out.println(bean.getName());
    }

运行结果
在这里插入图片描述
上述是展示了使用 ${} 的方式,平时还会使用到 #{} 的方式,该方法适用于 SpEL的方式,SpEL即可以适用于去获取一个外部bean的属性来给赋值
新建一个Role的类

package cn.songlinzi.beans;

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

/**
* @Author Joe
* cn.songlinzi.beans
* @Date 2021-11-28 21:12
*/
@Component
public class Role {
   @Value("管理员")
   private String name;

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }
}

User.java

package cn.songlinzi.beans;

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

/**
 * @Author Joe
 * cn.songlinzi.beans
 * @Date 2021-11-28 19:24
 */
@Component
public class User {
    //使用@Value设置依赖注入的属性
    //除了可以写硬编码值,还可以使用${}、#{},
    // ${}是用于引入外部的值,比如properties的文件中的key会引入value值
    // #{} 是用于SpEL表达式的时候有用到
//    @Value("张三")
//    @Value("${mysql.name}")
    @Value("#{role.name}")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

测试类

    @Test
    public void test04(){
        User bean = ioc.getBean("user",User.class);
        System.out.println(bean.getName());
    }

使用自动装配的方式

关键字:@Autowired
实例代码
UserController.java

package cn.songlinzi.controller;

import cn.songlinzi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
* @Author Joe
* cn.songlinzi.controller
* @Date 2021-11-28 19:10
*/
@Controller
public class UserController {
  @Autowired
  UserService userService;

  public void getUser(){
      userService.getUser();
  }
}

UserServiceImpl.java

package cn.songlinzi.service.impl;

import cn.songlinzi.dao.UserDao;
import cn.songlinzi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author Joe
 * cn.songlinzi.service.impl
 * @Date 2021-11-28 19:11
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Override
    public void getUser() {
        userDao.getUser();
    }
}

UserService.java

package cn.songlinzi.service;

/**
 * @Author Joe
 * cn.songlinzi.service
 * @Date 2021-11-28 19:10
 */
public interface UserService {
    void getUser();
}

测试类

    @Test
    public void test05(){
        UserController bean = ioc.getBean(UserController.class);
        bean.getUser();
    }

运行结果:
在这里插入图片描述
补充:
在使用@Autowired来实现自动注入

  • 默认优先根据类型去做匹配
  • 如果匹配到多个就会去根据名字匹配(此处的类型,指的就是通常去使用继承方式)
  • 如果名字有没有匹配到则会报错
    1. 可以去修改哦属性的名字对应的bean的名字 userServiceImpl
    2. 可以去修改bean的名字 对应属性的名字 @Service(“userService”)
    3. 可以通过@Qualifier(“userServiceImpl”)设置属性的名字(覆盖),找不到会直接报错
    4. 可以通过设置其中一个bean为自动注入主要的 @Primary
    5. 使用泛型作为自动注入限定符

注解中 @Autowired和@Resource的区别
1. @Resource 依赖JDK,@Autowired依赖Spring
2. @Resource 优先根据名字匹配
3. @Autowired 优先根据类型匹配

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值