Spring框架 步骤 概述与介绍(2)注解注入-程序员宅基地

技术标签: spring  java  后端  

1.@Component

*#本文为上课时实例,篇幅较长,请耐心查阅

(1)定义

创建对象,等同于功能

(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/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.dao"/>
</beans>

(5)核心代码TestSpring

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

3.@Service

(1)定义

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

(2)核心代码UserService

public interface UserService {
    
    public Integer addUser();
}

(3)核心代码UserServiceImpl

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

(4)核心代码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"/>
</beans>

(5)TestSpring

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

4.@Controller

(1)定义

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

(2)核心代码UserController

@Controller(value = "userController")
public class UserController {
    
    public Integer addUser(){
    
        System.out.println("调用userController.....");
        return 0;
    }
}

(3)核心代码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"/>
</beans>

(4)TestSpring

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

5.@Value

(1)定义

给简单类型属性对象赋值

(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
public class User   {
    
    @Value(value = "1")
    private Integer id;
    @Value(value = "zs")
    private String name;
	//注意:@Value等价于set()方法,无需再定义set()
    public Integer getId() {
    
        return id;
    }

    public String getName() {
    
        return 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("user");
        System.out.println(myUser.getId()+"    "+myUser.getName());
    }
}

6.@Autowired

(1)定义

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

(2)创建maven工程

(3)pom

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

(4.1)entity/User

package cn.kgc.entity;

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

@Component
public class User   {
    

    @Value(value = "1")
    private Integer id;
    @Value(value = "zs")
    private String name;
    @Autowired
    private Role role;

    @Autowired
    private SonRole sonRole;

    public SonRole getSonRole() {
    
        return sonRole;
    }

    public Role getRole() {
    
        return role;
    }

    public Integer getId() {
    
        return id;
    }

    public String getName() {
    
        return name;
    }
}

(4.2)entity/Role.

package cn.kgc.entity;

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

@Component
public class Role {
    
    @Value(value = "99")
    private Integer rId;
    @Value(value = "老师")
    private String rName;

    public Integer getrId() {
    
        return rId;
    }


    public String getrName() {
    
        return rName;
    }
}

(4.3)拓展 entity/SonRole

@Component
public class SonRole extends Role{
    

}

(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("user");
        System.out.println(myUser.getId()+"    "+myUser.getName()+" "+myUser.getRole().getrName()+" "+myUser.getSonRole().getrName());
    }
}

7.@Resource

(1)定义

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

(2)创建maven工程

(3)pom

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

(4.1)entity/User

package cn.kgc.entity;

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

import javax.annotation.Resource;

@Component
public class User   {
    
    @Value("11")
    private Integer id;
    @Value("zz")
    private String name;

    @Resource
    private Role role;

    public Role getRole() {
    
        return role;
    }

    public Integer getId() {
    
        return id;
    }

    public String getName() {
    
        return name;
    }
}

(4.2)entity/Role

package cn.kgc.entity;

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

@Component
public class Role {
    
    private Integer rId;
    @Value("李四")
    private String rName;

    public Integer getrId() {
    
        return rId;
    }

    public String getrName() {
    
        return rName;
    }
}

(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

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

7.2@Resource拓展

(1)创建maven工程

(2)pom

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

(3)entity/User

package cn.kgc.entity;

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

import javax.annotation.Resource;

@Component
public class User   {
    @Value("11")
    private Integer id;
    @Value("zz")
    private String name;

    @Resource
    private Role role33;

    public Role getRole33() {
        return role33;
    }

    public Integer getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

(4)entity/Role

package cn.kgc.entity;

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

@Component
public class Role {
    private Integer rId;
    @Value("李四")
    private String rName;

    public Integer getrId() {
        return rId;
    }

    public String getrName() {
        return rName;
    }
}

(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("user");
        System.out.println(myUser.getId()+"    "+myUser.getName()+" "+myUser.getRole33().getrName() );
    }
}

8.拓展:

@Component和@Repository,@Service,@Controller的异同
同:都可以创建对象
异:@Repository,@Service,@Controller都有自己的分层角色.
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/tmxk1998/article/details/121776072

智能推荐

没有U盘Win10电脑下如何使用本地硬盘安装Ubuntu20.04(单双硬盘都行)_没有u盘怎么装ubuntu-程序员宅基地

文章浏览阅读3.6k次,点赞2次,收藏2次。DELL7080台式机两块硬盘。_没有u盘怎么装ubuntu

【POJ 3401】Asteroids-程序员宅基地

文章浏览阅读32次。题面Bessie wants to navigate her spaceship through a dangerous asteroid field in the shape of an N x N grid (1 <= N <= 500). The grid contains K asteroids (1 <= K <= 10,000), which are conv...

工业机器视觉系统的构成与开发过程(理论篇—1)_工业机器视觉系统的构成与开发过程(理论篇—1-程序员宅基地

文章浏览阅读2.6w次,点赞21次,收藏112次。机器视觉则主要是指工业领域视觉的应用研究,例如自主机器人的视觉,用于检测和测量的视觉系统等。它通过在工业领域将图像感知、图像处理、控制理论与软件、硬件紧密结合,并研究解决图像处理和计算机视觉理论在实际应用过程中的问题,以实现高效的运动控制或各种实时操作。_工业机器视觉系统的构成与开发过程(理论篇—1

plt.legend的用法-程序员宅基地

文章浏览阅读5.9w次,点赞32次,收藏58次。legend 传奇、图例。plt.legend()的作用:在plt.plot() 定义后plt.legend() 会显示该 label 的内容,否则会报error: No handles with labels found to put in legend.plt.plot(result_price, color = 'red', label = 'Training Loss') legend作用位置:下图红圈处。..._plt.legend

深入理解 C# .NET Core 中 async await 异步编程思想_netcore async await-程序员宅基地

文章浏览阅读2.2k次,点赞3次,收藏11次。深入理解 C# .NET Core 中 async await 异步编程思想引言一、什么是异步?1.1 简单实例(WatchTV并行CookCoffee)二、深入理解(异步)2.1 当我需要异步返回值时,怎么处理?2.2 充分利用异步并行的高效性async await的秘密引言很久没来CSDN了,快小半年了一直在闲置,也写不出一些带有思想和深度的文章;之前就写过一篇关于async await 的异步理解 ,现在回顾,真的不要太浅和太陋,让人不忍直视!好了,废话不再啰嗦,直入主题:一、什么是异步?_netcore async await

IntelliJ IDEA设置类注释和方法注释带作者和日期_idea作者和日期等注释-程序员宅基地

文章浏览阅读6.5w次,点赞166次,收藏309次。当我看到别人的类上面的多行注释是是这样的:这样的:这样的:好装X啊!我也想要!怎么办呢?往下瞅:跟着我左手右手一个慢动作~~~File--->Settings---->Editor---->File and Code Templates --->Includes--->File Header:之后点applay--..._idea作者和日期等注释

随便推点

发行版Linux和麒麟操作系统下netperf 网络性能测试-程序员宅基地

文章浏览阅读175次。Netperf是一种网络性能的测量工具,主要针对基于TCP或UDP的传输。Netperf根据应用的不同,可以进行不同模式的网络性能测试,即批量数据传输(bulk data transfer)模式和请求/应答(request/reponse)模式。工作原理Netperf工具以client/server方式工作。server端是netserver,用来侦听来自client端的连接,c..._netperf 麒麟

万字长文详解 Go 程序是怎样跑起来的?| CSDN 博文精选-程序员宅基地

文章浏览阅读1.1k次,点赞2次,收藏3次。作者| qcrao责编 | 屠敏出品 | 程序员宅基地刚开始写这篇文章的时候,目标非常大,想要探索 Go 程序的一生:编码、编译、汇编、链接、运行、退出。它的每一步具体如何进行,力图弄清 Go 程序的这一生。在这个过程中,我又复习了一遍《程序员的自我修养》。这是一本讲编译、链接的书,非常详细,值得一看!数年前,我第一次看到这本书的书名,就非常喜欢。因为它模仿了周星驰喜剧..._go run 每次都要编译吗

C++之istringstream、ostringstream、stringstream 类详解_c++ istringstream a >> string-程序员宅基地

文章浏览阅读1.4k次,点赞4次,收藏2次。0、C++的输入输出分为三种:(1)基于控制台的I/O (2)基于文件的I/O (3)基于字符串的I/O 1、头文件[cpp] view plaincopyprint?#include 2、作用istringstream类用于执行C++风格的字符串流的输入操作。 ostringstream类用_c++ istringstream a >> string

MySQL 的 binglog、redolog、undolog-程序员宅基地

文章浏览阅读2k次,点赞3次,收藏14次。我们在每个修改的地方都记录一条对应的 redo 日志显然是不现实的,因此实现方式是用时间换空间,我们在数据库崩了之后用日志还原数据时,在执行这条日志之前,数据库应该是一个一致性状态,我们用对应的参数,执行固定的步骤,修改对应的数据。1,MySQL 就是通过 undolog 回滚日志来保证事务原子性的,在异常发生时,对已经执行的操作进行回滚,回滚日志会先于数据持久化到磁盘上(因为它记录的数据比较少,所以持久化的速度快),当用户再次启动数据库的时候,数据库能够通过查询回滚日志来回滚将之前未完成的事务。_binglog

我的第一个Chrome小插件-基于vue开发的flexbox布局CSS拷贝工具_chrome css布局插件-程序员宅基地

文章浏览阅读3k次。概述之前介绍过 移动Web开发基础-flex弹性布局(兼容写法) 里面有提到过想做一个Chrome插件,来生成flexbox布局的css代码直接拷贝出来用。最近把这个想法实现了,给大家分享下。play-flexbox插件介绍play-flexbox一秒搞定flexbox布局,可直接预览效果,拷贝CSS代码快速用于页面重构。 你也可以通过点击以下链接(codepen示例)查_chrome css布局插件

win10下安装TensorFlow-gpu的流程(包括cuda、cuDnn下载以及安装问题)-程序员宅基地

文章浏览阅读308次。我自己的配置是GeForce GTX 1660 +CUDA10.0+CUDNN7.6.0 + TensorFlow-GPU 1.14.0Win10系统安装tensorflow-gpu(按照步骤一次成功)https://blog.csdn.net/zqxdsy/article/details/103152190环境配置——win10下TensorFlow-GPU安装(GTX1660 SUPER+CUDA10+CUDNN7.4)https://blog.csdn.net/jiDxiaohuo/arti