Spring框架之注解注入

这篇博客详细介绍了Spring框架中的注解注入,包括@Component、@Repository、@Service、@Controller的定义、使用场景及核心代码示例。此外,还探讨了@Value和@Autowired的自动装配功能,以及@Resource的按名称或类型的注入方式。最后,文章对比了@Component及其派生注解在不同层面上的作用。
摘要由CSDN通过智能技术生成

1.@Component

(1)定义

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

(2)创建maven工程

(3)pom

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>

(4)entity并加入注解

package cn.kgc.entity;

import org.springframework.stereotype.Component;

@Component(value = "myUser")
public class User   {
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

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

(6)测试类TestSpring

package cn.kgc.test;

import cn.kgc.entity.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring {
    @Test
    public void testdemo001(){
        String conf = "applicationContext.xml";
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(conf);
        User myUser = (User) ac.getBean("myUser");
        System.out.println(myUser);
    }
}

(7)拓展

第一种拓展:@Component( "myUser")
第二种拓展:@Component

2.@Repository

(1)定义

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

(2)核心代码UserMapper.java

public interface UserMapper {
    public Integer addUser();
}

(3)核心代码UserMapperImpl.java

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

(4)核心代码applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值