Spring中基于注解的IOC配置项目举例详解

文章目录

  • Spring中基于注解的IOC配置项目举例详解
    • 1、创建如下结构的Spring项目
      • pom.xml
      • dao层
      • service层
      • application.xml
      • log4j.properties
    • 2、用于创建对象的常用注解
      • 2.1、@Controller或@Controller("user")声明bean,且id="user"
      • 2.2、@Service或用@Service("user")声明bean,且id="user"
      • 2.3、@Repository或同上面两个
      • 2.4、@Component
      • 2.5、@Scope
      • 以上几个注解功能相同,但为了在项目实现过程中便于区分则一般按照下面分类使用
    • 3、用于属性注入的注解
      • 3.1、@Autowired
      • 3.2、@Resource
      • 3.3、@Value
    • 测试类

Spring中基于注解的IOC配置项目举例详解

1、创建如下结构的Spring项目

在这里插入图片描述

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>SpringDemo</artifactId><groupId>cn.fpl</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>Spring_IOC_Annotation</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.1.8.RELEASE</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.30</version></dependency></dependencies>
</project>

dao层

public class UserDaoImpl implements UserDao {@Overridepublic void addUser(){System.out.println("insert into tb_user......");}
}

service层

public class UserServiceImpl implements UserService {@Overridepublic void addUser(){System.out.println(userDao+"       "+name+"      "+age);userDao.addUser();}
}

application.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd "><!--告诉spring,容器启动时要扫描的包,且spring会依据注解创建对象并存到IOC容器中--><context:component-scan base-package="cn.fpl"></context:component-scan>
</beans>

log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

2、用于创建对象的常用注解

2.1、@Controller或@Controller(“user”)声明bean,且id=“user”

  • 作用:

    把资源交给spring来管理,相当于:<bean id="" class="">;一般用于表现层。

  • 属性:

    value:指定bean的id;如果不指定value属性,默认bean的id是当前类的类名首字母小写

2.2、@Service或用@Service(“user”)声明bean,且id=“user”

  • 作用:

    把资源交给spring来管理,相当于:<bean id="" class="">;一般用于业务层。

  • 属性:

    value:指定bean的id;如果不指定value属性,默认bean的id是当前类的类名首字母小写

2.3、@Repository或同上面两个

  • 作用:

    把资源交给spring来管理,相当于:<bean id="" class="">;一般用于持久层。

  • 属性:

    value:指定bean的id;如果不指定value属性,默认bean的id是当前类的类名,首字母小写

    2.4、@Component

    • 作用:

    把资源交给spring来管理,相当于:<bean id="" class="">;通用。

  • 属性:

    value:指定bean的id;如果不指定value属性,默认bean的id是当前类的类名,首字母小写;

    2.5、@Scope

    • 作用:

    指定bean的作用域范围。

  • 属性:

    value:指定范围的值,singleton prototype request session。

    以上几个注解功能相同,但为了在项目实现过程中便于区分则一般按照下面分类使用

@Controller:web
@Service:service
@Repository:dao
@Component:三层架构之外

3、用于属性注入的注解

以下四个注解的作用相当于:<property name="" ref="">

3.1、@Autowired

作用:

自动按照类型注入。set方法可以省略。

案例:

@Service
public class UserServiceImpl implements UserService {@Autowired //注入类型为UserDAO的beanprivate UserDao userDao;public void addUser(){userDao.addUser();}
}

3.2、@Resource

  • 作用:

    自动按照名字注入。set方法可以省略。

  • 属性:

​ name:指定bean的id。

案例:

@Service
public class UserServiceImpl implements UserService {@Resource(name="userDaoImpl")//注入id=“userDaoImpl”的beanprivate UserDao userDao;public void addUser(){userDao.addUser();}
}

3.3、@Value

  • 作用:

    注入基本数据类型和String类型数据的

  • 属性:

​ value:用于指定值

  • 案例一
@Service
public class UserServiceImpl implements UserService {@Resource(name="userDaoImpl") //注入id=“userDaoImpl”的beanprivate UserDao userDao;@Value("张三")//注入Stringprivate String name;@Value("18")//注入Integerprivate Integer age;public void addUser(){System.out.println(name+","+age);userDao.addUser();}
}
  • 案例二
  • 创建config.properties文件在resources文件夹下
name=张三
age=18
  • 在application.xml文件中加载配置文件
<!--加载config.properties配置文件,并把配置文件中的数据存到IOC容器中--><context:property-placeholder location="config.properties"></context:property-placeholder>
  • 注入属性值
@Service
public class UserServiceImpl implements UserService {@Autowiredprivate UserDao userDao;@Value("${name}")//注入Stringprivate String name;@Value("${age}")//注入Integerprivate Integer age;public void addUser() {System.out.println(name+","+age);userDao.addUser();}
}

测试类

public static void main(String[] args) {ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");UserDao userDao = ac.getBean("userDaoImpl", UserDao.class);UserService userService = ac.getBean("user", UserService.class);userService.addUser();}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/321246.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

可狱可囚的爬虫系列课程 08:新闻数据爬取实战

前言 本篇文章中我带大家针对前面所学 Requests 和 BeautifulSoup4 进行一个实操检验。 相信大家平时或多或少都有看新闻的习惯&#xff0c;那么我们今天所要爬取的网站便是新闻类型的&#xff1a;中国新闻网&#xff0c;我们先来使用爬虫爬取一些具有明显规则或规律的信息&am…

Linux进程以及计划服务(二)

一.控制进程 前台运行&#xff1a;通过终端启动&#xff0c;且启动后一直占据终端&#xff08;影响当前终端的操作&#xff09; 后台运行&#xff1a;可通过终端启动&#xff0c;但启动后即转入后台运行&#xff08;不影响当前终端的操作&#xff09; 1.手动启动 前台启动&…

SwiftUI之深入解析ContentUnavailableView的实战应用

一、基本用法 SwiftUI 引入了新的 ContentUnavailableView 类型&#xff0c;允许在应用程序中展示空状态、错误状态或任何其他内容不可用的状态。那么&#xff0c;如何使用 ContentUnavailableView 引导用户浏览应用程序中的空状态呢&#xff1f;首先看看 ContentUnavailableV…

3D目标检测(教程+代码)

随着计算机视觉技术的不断发展&#xff0c;3D目标检测成为了一个备受关注的研究领域。与传统的2D目标检测相比&#xff0c;3D目标检测可以在三维空间中对物体进行定位和识别&#xff0c;具有更高的准确性和适用性。本文将介绍3D目标检测的相关概念、方法和代码实现。 一、3D目…

Python-1-字符串类型及方法

众所周知&#xff0c;Python面向对象&#xff0c;功能强大 | ू•ૅω•́)ᵎᵎᵎ

某和医院招采系统web端数据爬取, 逆向js

目标网址:https://zbcg.sznsyy.cn/homeNotice 测试时间: 2024-01-03 1 老规矩,打开Chrome无痕浏览,打开链接,监测网络,通过刷新以及上下翻页可以猜测出数据的请求是通过接口frontPageAnnouncementList获取的,查看返回可以看出来数据大概率是经过aes加密的,如图: 通过查看该请…

FLatten Transformer:聚焦式线性注意力模块

线性注意力将Softmax解耦为两个独立的函数&#xff0c;从而能够将注意力的计算顺序从(querykey)value调整为query(keyvalue)&#xff0c;使得总体的计算复杂度降低为线性。然而&#xff0c;目前的线性注意力方法要么性能明显不如Softmax注意力&#xff0c;并且可能涉及映射函数…

搜维尔科技:【简报】第九届元宇宙数字人设计大赛,报名已经进入白热化阶段!

随着元宇宙时代的来临&#xff0c;数字人设计成为了创新前沿领域之一。为了提高大学生元宇宙虚拟人角色策划与美术设计的专业核心能力&#xff0c;我们特别举办了这场元宇宙数字人设计赛道&#xff0c;赛道主题为「AI人工智能科技」 &#xff0c;只要与「AI人工智能科技」相关的…

SpringBoot项目处理 多数据源问题(把本地库数据 推送 到另外一个平台的库)

一、需求梳理 把我方数据库的表中数据 ----------> 推送到第三方的数据库 相当于库对库的数据插入, 但是需要的是用代码的方式实现; 二、解决思维 (1) 首先,平台与平台之间的数据库对接; 处理点1: 字段转换 (库表之间的数据字段不一致问题) 解决方式: 挨个字段的对应,如…

es索引数据过滤查询

1.我们往kibana插入数据,来进行查询 POST /t1/_doc/ {"name":"cat","age":"18","address":"BJ","job":"dev" } POST /t1/_doc/ {"name":"dog","age":"1…

雍禾医疗亮相博鳌论坛 雍禾植发让小城市也能治“毛”病

颜值经济时代&#xff0c;伴随着居民消费水平的提高与受脱发困扰群体的逐步扩张&#xff0c;人们对毛发健康与毛发美观的关注度日益增长。需求催生了毛发医疗行业的飞速发展&#xff0c;为脱发群体提供爱美、求美、变美的新思路、新契机。 近期&#xff0c;2023中国企业家博鳌…

第一部分:vue学习(26-x)

文章目录 26.绑定class样式27 绑定style内联样式28 条件渲染29 列表渲染 26.绑定class样式 案例1&#xff1a;点击切换class样式。其中noarmal happy都是css定义好的样式。 案例2&#xff1a;切换随机的样式。 案例3&#xff1a;css样式&#xff0c;列表生效 案例4&#xff1…