Spring 2 - 注解注入

本文详细介绍了Spring Boot中四种常用注解(@Component, @Repository, @Service, @Controller)的区别与使用,以及@Resource的独特之处。通过实例演示了如何在Maven工程中配置和测试这些注解的应用。

1. @Component

1.1 定义

创建对象,等同于<bean></bean>功能

1.2 创建maven工程

src/main/java/cn.kgc/…
src/main/resources/…
src/test/java/cn.kgc.test/…

1.3 pom.xml

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.5</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.20</version>
      <scope>provided</scope>
</dependency>

1.4 entity并加入注解

@Getter
@Setter
@Component(value = "user")
public class User {
    private Integer id;
    private String name;
}

1.5 applicationContext.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">
    <!--声明组件扫描器-->
    <context:component-scan base-package="cn.kgc.entity" />
</beans>

以上的作用是将某个对象作为Bean注入进Spring容器。

1.6 测试类Test01

@Test
public void test01(){
    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    User user = (User) ac.getBean("user");
    System.out.println(user);
}

结果: cn.kgc.entity.User@3ec300f1

1.7 拓展

第一种拓展(省略value): @Component( “myUser”)
第二种拓展(都省略,但是默认的不能随便写): @Component

2. @Repository

2.1 定义

用在持久层上面,方法在dao的实现类上面,表示创建dao对象

2.2 UserMapper.java

public interface UserMapper {
    Integer addUser();
}

2.3 UserMapperImpl.java

@Repository(value = "userMapper")   
//在申明XXMapper的bean对象的时候,@Respository中的value不建议省略
public class UserMapperImpl implements UserMapper {
    @Override
    public Integer addUser() {
        System.out.println("调用持久层方法。。。");
        return null;
    }
}

2.4 applicationContext.xml

 <!--声明组件扫描器-->
<context:component-scan base-package="cn.kgc.dao"/>
或者
<context:component-scan base-package="cn.kgc.entity;cn.kgc.dao" />
    <!--    cn.kgc 也可以 但耗资源 慢慢扫-->

2.5 Test01

@Test
    public void test02(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = (UserMapper) ac.getBean("userMapper");
        userMapper.addUser();
}

这边也可以写UserMapperImpl,因为注解是在这个类里的,
但没意义了,就体现不出接口了。

结果: 调用持久层方法。。。

3. @Service(常见)

3.1 定义

用在业务层上面,放在service的实现类上面,
表示创建service对象,可以有一些事务功能

3.2 核心代码UserService

public interface UserService {
    public Integer addUser();
}

3.3 核心代码UserServiceImpl

import org.springframework.stereotype.Service;

@Service(value = "userService")
public class UserServiceImpl implements UserService {
    @Override
    public Integer addUser() {
        System.out.println("调用UserService()方法");
        return null;
    }
}

3.4 核心代码applicationContext.xml

<!--声明组件扫描器-->
<context:component-scan base-package="cn.kgc"/>

3.5 Test01

@Test
    public void test03(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) ac.getBean("userService");
        userService.addUser();
}

结果: 调用UserService()方法

4. @Controller(常用)

4.1 定义

用在控制器上面,放在控制器上面,创建控制前对象,
能够接受用户提交的参数,显示请求的处理结果

4.2 核心代码UserController

import org.springframework.stereotype.Controller;
@Controller(value = "userController")
public class UserController {
    public Integer addUser(){
       System.out.println("调用userController的addUser()方法");
        return 0;
    }
}

4.3 核心代码applicationContext.xml

<!--声明组件扫描器-->
<context:component-scan base-package="cn.kgc"/>

4.4 Test01.java

@Test
    public void test04(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserController userController = (UserController) ac.getBean("userController");
        userController.addUser();
}

结果: 调用userController的addUser()方法

5. @Value

5.1 定义

给简单类型属性对象赋值

5.2 根据@Component例子继续写

》User并加入注解

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Getter
@Setter
@Component(value = "user")
public class User {
    @Value(value = "1")
    private Integer id;
    @Value(value = "阿斯顿")
    private String name;
//注意:@Value等价于set()方法,无需再定义set()
}    

5.3 测试类Test01

@Test
    public void test05(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = (User) ac.getBean("user");
        System.out.println("id:" + user.getId() + "    name:" + user.getName());
}

结果: id:1 name:阿斯顿

上面是注入简单类型

下面是注入引用类型

6. @Autowired(常见)

6. 1 定义

给引用类型属性赋值(自动装配Bean),使用,默认使用byType自动注入。

6. 2 创建maven工程

6. 3 pom

 <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.5</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.20</version>
      <scope>provided</scope>
</dependency>

6. 4 entity/User

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Getter
@Setter
@Component(value = "user")
public class User {
    @Value(value = "1")
    private Integer id;
    @Value(value = "你啊")
    private String name;
    @Autowired
    //是根据类型的,所以类名写错也没事
    private Role role;
}

6.4.2 entity/Role

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Setter
@Getter
@Component
public class Role {
    @Value(value = "100")
    private Integer rId;
    @Value(value = "应届生")
    private String rName;
}

6.4.3 拓展 entity/SonRole

@Component
public class SonRole extends Role{ }

entity/User

@Autowired
private SonRole sonRole;

test/…/TestSpring

System.out.println("name:" + user.getName() + "    rName:"+user.getSonRole().getRName());

6. 5 applicationContext.xml加入组件扫描器

<!--声明组件扫描器-->
<context:component-scan base-package="cn.kgc" />

6. 6 测试类TestSpring

    @Test
    public void demo01(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = (User) ac.getBean("user");
        System.out.println("name:" + user.getName() + "    rName:"+user.getRole().getRName());
}

结果: name:你啊 rName:应届生

7. @Resource(常用)

7. 1 定义–>不是spring注解

给引用类型赋值,Spring提供了对JDK注解@Resource的支持,
默认按名称注入,如果按名称注入失败,自动按类型注入

7. 2 创建maven工程

7. 3 pom.xml(省略)

7. 4 entity/User

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Getter
@Setter
@Component(value = "user")
public class User {
    @Value(value = "1")
    private Integer id;
    @Value(value = "你啊")
    private String name;
    @Resource
private Role role;
}

7.4.1 entity/Role

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Setter
@Getter
@Component
public class Role {
    @Value(value = "100")
    private Integer rId;
    @Value(value = "应届生")
    private String rName;
}

7.5 applicationContext.xml加入组件扫描器

<context:component-scan base-package="cn.kgc.entity" />

7.6 测试类TestSpring

public class TestSpring {
    @Test
    public void testdemo001(){
        String conf = "applicationContext.xml";
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        User user = (User) ac.getBean("user");
        System.out.println("name:" + user.getName() + "    rName:"+user.getRole().getRName());
    }
}

结果: name:你啊 rName:应届生

对于杠精,偏偏想名撑和类名不一致,
如下resources哪怕是错的也能输出。

8. @Resource 拓展

8.1 创建maven工程

8.2 pom(省略)

8.3 entity/User

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

import javax.annotation.Resource;
@Component (value = "user")
public class User   {
    @Value(value = "1")
    private Integer id;
    @Value(value = "你啊")
    private String name;
@Resource 
    private Role role33;

    public Role getRole33() { return role33; }

    public Integer getId() { return id; }

    public String getName() { return name; }
}

8.4 entity/Role

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

@Component
public class Role {
    @Value(value = "100")
    private Integer rId;
    @Value(value = "应届生")
private String rName;

    public Integer getrId() {
        return rId;
    }

    public String getrName() {
        return rName;
    }
}

8.5 applicationContext.xml加入组件扫描器

<!--声明组件扫描器-->
<context:component-scan base-package="cn.kgc.entity"/>

8.6 测试类TestSpring

  @Test
    public void testdemo01(){
      ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = (User) ac.getBean("user");
        System.out.println("name:"+user.getName()+"    rName:"+user.getRole33().getrName() );
} 

结果: name:你啊 rName:应届生

9. 拓展:

@Component和@Repository,@Service,@Controller的异同

:都可以创建对象

:@Component,@Repository,@Service,@Controller都有自己的分层角色.
@Component 》实体类层
@Repository 》dao层
@Service 》service层
@Controller 》 controller层

注意点: 只是一种规范,其实用啥都行。

题外话:
实现类之间@xxx(value = “”)中的value不能省,
单单一个类可以。

----2021.12.07

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值