spring_day02_基于注解的spring配置

springday02 DI依赖注入,通过set方法注入和通过构造方法注入的练习 立即下载

一、前提

注解配置和xml配置要实现的功能都是一样的,都是要降低程序间的耦合,只是配置的形式不一样

实际的开发中到底使用xml还是注解,每家公司有着不同的使用习惯

二、入门

1、环境搭建

1.1 导入jar包

在基于注解的配置中,我们还要多拷贝一个aop的jar包

 1.2 添加约束

xmlns:context="http://www.springframework.org/schema/context"

<?xml version="1.0" encoding="UTF-8"?>
<!-- 导入schema 约束的位置在: ..\spring-framework-4.2.4.RELEASE\docs\spring-framework-reference\html\xsd-configuration.html 
	文件中 -->
<!-- 注意:要导入schema约束 -->
<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/beans
      			http://www.springframework.org/schema/beans/spring-beans.xsd
				http://www.springframework.org/schema/context
      			http://www.springframework.org/schema/context/spring-context.xsd ">
</beans>

1.3 开启spring对注解ioc的支持

开启注解组件扫描

<context:component-scan base-package="com.itheima"/>

<?xml version="1.0" encoding="UTF-8"?>
<!-- 导入schema 约束的位置在: ..\spring-framework-4.2.4.RELEASE\docs\spring-framework-reference\html\xsd-configuration.html 
	文件中 -->
<!-- 注意:要导入schema约束 -->
<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/beans
      			http://www.springframework.org/schema/beans/spring-beans.xsd
				http://www.springframework.org/schema/context
      			http://www.springframework.org/schema/context/spring-context.xsd ">

	<!-- 告知spring框架在读取配置文件,创建容器时,扫描注解,依据注解创建对象,并存入容器中 -->
	<context:component-scan base-package="com.itheima"/>

</beans>

1.4 编写java类

import org.springframework.stereotype.Component;

@Component(value="userService")// 不写的时候,默认的id是:当前类名,且首字母小写
public class UserServiceImpl implements UserService {

	@Override
	public void saveUser() {
		System.out.println("添加用户");
	}

}
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.itheima.service.UserService;

public class TestAnnotation {

	@Test
	public void testName() throws Exception {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

		UserService service = (UserService) applicationContext.getBean("userService");
		
		service.saveUser();
	}

}

三、常用注解

1、类上的注解

1.1 创建对象的

  • @Component
    • Spring中提供@Component的三个衍生注解
      • @Controller       -- 作用在WEB层
      • @Service          -- 作用在业务层
      • @Repository       -- 作用在持久层

1.2 生命周期

  • @Scope(value="prototype")
    • 指定bean的作用范围
    • 取值
      • singleton---单例模式,默认,service,dao层
      • prototype--多例模式,web层
      • reques
      • session
      • globalsession
  • @PostConstruct
    • 指定初始化方法
  • @PreDestroy
    • 指定销毁方法

2、依赖注入

2.1 普通值

  • @Value("普通值")

2.2 引用值

  • 按照类型注入
    • @Autowired
  • 按照名称注入
    • @Autowired
    • @Qualifier("名称")
  • 按照名称注入
    • @Resource("名称")

3、如何选择

注解的优势

配置简单,维护方便(我们找到类,就相当于找到了对应的配置)

XML的优势

修改时,不用改源码

4、注解和XML混合使用

  1. 将所有的bean都配置在XML文件中
  2. 将所有的依赖都使用注解
  3. 在核心配置文件中,添加<context:annotation-config/>(只能使注入注解生效)
  4. <context:component-scan base-package="com.itheima"/>可以使@Component生效,注入注解自动生效

spring纯注解配置

类上

  • @Configuration
    • 用于指定当前类是一个配置类,会从该类上加载注解。读取该类上@ ComponentScan注解初始化spring容器
  • PropertySource
    • 加载.properties文件中的配置
    • value[]:用于指定properties文件位置。如果是在类路径下,需要写上classpath:
  • @Import(C3P0Utils.class)
    • 导入其他配置类
  • @ComponentScan
    • 用于指定spring在初始化容器时要扫描的包
      • basePackages:用于指定要扫描的包。和该注解中的value属性作用一样
      • value:用于指定要扫描的包,是一个数组类型

方法上

  • @Bean
  • 使用此方法创建一个对象,并且放入spring容器
    • name:给当前@Bean注解方法创建的对象指定一个名称(即bean的id)

案例

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration // 当前类是一个配置类
@ComponentScan(basePackages = "com.itheima") // 配置需要扫描注解的包
public class SpringConfiguration {

	@Bean// 在spring4.3以前都需要提供一个占位符配置器,开启@PropertySource注解
	public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
		return new PropertySourcesPlaceholderConfigurer();
	}

}
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/crm
jdbc.username=root
jdbc.password=root

 

import javax.sql.DataSource;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component(value = "c3p0Utils")
@PropertySource("classpath:jdbc.properties")
public class C3P0Utils {

	@Value("${jdbc.driver}")
	private String driver;
	@Value("${jdbc.url}")
	private String url;
	@Value("${jdbc.username}")
	private String username;
	@Value("${jdbc.password}")
	private String password;

	@Bean(name = "datasource")
	public DataSource getDataSource() {
		BasicDataSource ds = new BasicDataSource();
		ds.setDriverClassName(driver);
		ds.setUrl(url);
		ds.setUsername(username);
		ds.setPassword(password);
		return ds;
	}

}
import javax.sql.DataSource;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.itheima.config.SpringConfiguration;
import com.itheima.service.UserService;

public class TestAnnotation {

	@Test
	public void test() throws Exception {
		
		ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
		
		DataSource ds = (DataSource) ac.getBean("datasource");
		
		System.out.println(ds.getConnection());

	}

}

spring整合junit测试

导入jar包

spring-test-4.2.4.RELEASE.jar

import java.util.List;

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

import com.itheima.dao.UserDao;
import com.itheima.domain.User;

@Component(value="userService")
public class UserServiceImpl implements UserService {
	
	@Autowired
	private  UserDao userDao;

	@Override
	public void saveUser() {
		userDao.saveUser();
	}

	@Override
	public List<User> findAllUser() {
		return userDao.findAllUser();
	}

}
import java.util.List;

import org.springframework.stereotype.Repository;

import com.itheima.domain.User;

@Repository
public class UserDaoImpl implements UserDao {

	@Override
	public void saveUser() {
		System.out.println("添加用户成功");
	}

	@Override
	public List<User> findAllUser() {
		System.out.println("查找所有用户");
		return null;
	}

}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.itheima.service.UserService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={UserServiceTest.class})
@Configuration
@ComponentScan("com.itheima")
public class UserServiceTest {

	@Autowired
	private UserService service;
	@Test
	public void testSaveUser() throws Exception {
		service.saveUser();
	}
}

 

SVM-支持向量机学习(1):线性可分SVM的基本型 1. foreword先看的是李航老师的书第7章,比较传统按照以下三节展开: 线性可分SVM 线性SVM 非线性SVM SMO算法 李航老师讲东西向来不拖泥带水,但本节也几乎用了40页的篇幅,足见涉及内容之多。7月底硬着头皮啃了下来,边看边在笔记上摘抄标注,花了2天时间对SVM有了基本认识。一个月过去了,如今重新整理为博客,再看轻松许多,并不断对比西瓜书的内容,启望达到融会贯通。西瓜书此节明显节奏轻 阅读详情

相关推荐

深入解析UVM寄存器模型:reg2bus与bus2reg的隐式调用机制

本文深入解析了UVM寄存器模型中reg2bus与bus2reg函数的隐式调用机制。通过追踪一次寄存器访问的完整旅程,揭示了这两个关键函数是如何在uvm_reg_map和uvm_reg_predictor中被框架自动调用的,从而在抽象的寄存器操作与具体总线事务之间完成转换,并实现镜像值的自动更新。掌握此机制是高效调试和灵活应用UVM寄存器模型的基础。

weixin_29211309的博客 452

Spring注解开发

就相当于由于使用了Java配置类替代配置文件,所以读取spring核心配置文件初始化容器对象切换为读取Java配置类初始化容器对象。同时,在核心配置文件中通过扫描组件加载bean(在类中使用@Component注解,而在容器中需要找到这个bean)1所述方法虽然用到了@component注解简化了配置,但在配置文件中仍需要写出扫描的范围。@Service :用于业务层bean定义。

ruoxiuqaq的博客 135

SAP 对接CBS(http方式)

CLEAR:lv_xml_crc32_string. CONCATENATEcrc32_passwordcrc32_keyi_stringINTOlv_xml_crc32_string. CONDENSElv_xml_crc32_string. CALLFUNCTION'SCMS_STRING_TO_XSTRING' EXPORTING text=lv_xml_crc32_string encoding='8400' "GB...

3607

第5篇 基于注解的 IOC 配置

第5篇 基于注解的 IOC 配置 1 明确:写在最前 学习基于注解的 IoC 配置,大家脑海里首先得有一个认知,即注解配置和 xml 配置要实现的功能都是一样 的,都是要降低程序间的耦合。只是配置的形式不一样。 关于实际的开发中到底使用xml还是注解,每家公司有着不同的使用习惯。所以这两种配置方式我们都需要掌 握。 我们在讲解注解配置时,采用上一章节的案例,把 spring 的 xml ...

生锈的齿轮 288

毕设别再硬肝了:我用 GPT + Codex 做项目、写论文,效率直接起飞

这个也是神器。你项目做完之后,最怕的是老师一问就懵。这时候你直接把你的项目发给它,让它模拟老师提问。这是我的毕业设计题目和项目简介,请你站在答辩老师角度,提出20个高频问题,并给出简洁好背的回答。要求:问题尽量贴近计算机专业本科毕业答辩。为什么选这个题目?技术选型为什么这样定?你的创新点是什么?系统难点是什么?数据库怎么设计的?你的模型为什么选这个?如果继续优化,下一步怎么做?这个对答辩真的帮助很大。说实话,如果没有 GPT + Codex,

m0_74100417的博客 1889

PCIe信号眼图总是不开?手把手教你调CTLE和DFE参数(附实测波形对比)

本文详细解析了PCIe信号眼图调试中CTLE和DFE参数的优化方法,帮助硬件工程师解决眼图无法张开的问题。通过实际案例和步骤指导,介绍了如何调整CTLE直流增益和DFE抽头系数,提升接收端均衡器性能,确保信号完整性。

weixin_26805597的博客 231

JavaEE学习日志(八十九): spring注解开发详解

JavaEE学习日志(八十九) Spring注解开发: 注解开发入门, Component注解, 自动注入@Autowired, 自动注入@Resource, 使用半注解半xml改造账户CRUD, 纯注解开发案例, 使用纯注解改造账户CRUD, 改造纯注解, xml引入外部文件。

Sakuraaaaaaa的博客 318

Java 简易版 UDP 多人聊天室

【代码】Java 简易版 UDP 多人聊天室。

nmy15570188135的博客 1191

SpringMVC 组件解析

无

LY3054404567的博客 310

【Codecs系列】x265编码器(十二):子像素运动搜索

在基于块运动补偿的视频编码框架中,运动搜索是最为重要的环节之一,同时也是编码端最为耗时的模块。运动搜索包括整像素运动搜索和子像素运动搜索,其中整像素运动搜索已经有很多快速算法,比如经典的三步搜索法、菱形搜索、六边形搜索以及TZSearch等等;但子像素搜索的快速算法却比较少,本文主要讲解x265编码器中的子像素搜索方法以及相关的快速搜索方法。

CSDN明星博主,认证博客专家,视频、Matlab领域优质创作者。 758

Q3D提取PCB走线RLCG参数

介绍一种提取PCB走线寄生电容和寄生电感的方法

sinat_15150363的博客 2952

Spring扫描组件<context:component-scan base-package=" "/>的使用详解

1.如果不想在xml文件中配置bean,我们可以给我们的类加上spring组件注解,只需再配置下spring的扫描器就可以实现bean的自动载入。 需要注意的是: 在base-package指明一个包: 表明com.b505包及其子包中,如果某个类的头上带有特定的注解 @Component,@Repository,@Service,@Controller,就会将

冰冻非一日之寒 4万+

数据挖掘7、银行精准营销

利用数据挖掘技术,对银行已有数据进行分析,对客户进行识别,对客户是否能够进行存款精准营销Windows11。

m0_63099685的博客 399

[Spring]Day 02-使用注解配置Spring

Spring注解的基础使用 1.关键jar包 <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> 2.applica...

tinfengyee的博客 152

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

Spring——day02配置的相关注解

@Configuration:指定当前类为配置类(注意:当配置类为AnnotationConfigApplicationContext对象创建的参数时,可不写) @ComponentScan(value="packagename") 指定spring在创建容器时要扫描的包,等价于<context:component-scan base-package="com.kunjava"></context:component-scan> @Bean("aliasName"):当前类中的

qq_28933803的博客 155

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

Spring框架学习day02 基于注解的IOC配置

Spring框架学习day02 基于注解的IOC配置spring中ioc的常用注解spring中的其他注解Spring 整合 Junit 的问题分析 spring中ioc的常用注解 曾经xml的配置: <bean id="accountService" class="cn.itcast.service.impl.AccountServiceImpl" scope="" init-meth...

weixin_46539792的博客 291

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

Spring学习day02(基于注解的IOC配置、Spring整合Junit)

前言 建议先看上篇文章(Spring学习day01)点击访问 首先复习一下之前的Spring基于xml的IOC配置(通过一个案例),这里需要说明的是:spring的IOC并不能实现持久层的操作,而是能够将应用程序的配置和依赖性规范与实际的应用程序代码分开(控制反转),通过IOC将持久层的操作进行解耦,能优化整个操作。 一、案例:使用spring的IoC的实现账户的CRUD 通过spring的IOC...

qq_34504626的博客 344

Spring day02 注解配置,增删改查,整合junit

细节:当我们使用注解配置方法时,诶过方法有参数,spring框架会去容器中查找有没有可用的bean对象,查找的方式和Autowired注解的作用是一样的。另外,集合类型的注入只能通过XML来实现。* 当我们使用Import的注解之后,有Import注解的类就是主配置(父配置类),而导入的都是子配置类。* 他们的作用就和在xml配置文件中的bean标签中写一个(property)标签的作用是一样的。

Anyway_01的博客 983

Spring 学习笔记(day02)

文章目录spring-day021 使用注解配置spring1.1 步骤1.2 将对象注册到容器1.3 修改对象的作用范围1.4 值类型注入1.4 引用类型注入1.5 初始化|销毁方法2 spring与junit整合测试3 spring中的aop3.2 spring中的aop概念![在这里插入图片描述](https://img-blog.csdnimg.cn/20190715112715930.p...

求学之路的苦行僧 323

spring框架——day02常用配置和注解

一,SpringMVC常用配置 1.springmvc默认加载的配置文件是WEB-INF下的springmvc-servlet.xml,而我们通常将配置文件放在项目的资源目录中,即classpath下,因此需要配置springmvc加载的配置文件地址。 将配置文件转移至resources中,改名,并修改web.xml: springmvc org.springframework.web.serv...

weixin_30307921的博客 104

day52 JavaWeb框架阶段——Spring02(Spring配置数据源,Spring注解开发,Spring整合Junit)

1.Spring配置数据源 今日源码 : 链接:https://pan.baidu.com/s/1CYrFP9SpryKgPdXsJr4s-A 提取码:gjm7 1.1 数据源(连接池)的作用 数据源(连接池)是提高程序性能如出现的 事先实例化数据源,初始化部分连接资源 使用连接资源时从数据源中获取 使用完毕后将连接资源归还给数据源 常见的数据源(连接池):DBCP、C3P0、BoneCP、Dru...

qq_38454176的博客 306

SSH Struts2 JSON响应、注解配置 Struts2+Spring 整合day-02

JSON响应 Struts2中提供了一个json类型的Result,可以生成JSON字符串响应。需要引入struts2-json-plugin.jar包,在json-default包中。 返回Action获取的多个属性信息 /json1.do-->StrutsPrepareAndExecuteFilter-->Action-->Result-->生成JSON响应 1...

qq_35206389的博客 389

Day48-Spring-02 - IOC注解开发 - Spring测试 - AOP开发(配置方式)

Day48-Spring-02 - IOC注解开发 - Spring测试 - AOP开发(配置方式)

jjizh的博客 398

Spring(day02)(此篇附助于理解)(使用IOC完成CRUD未用到Mybatis)基于注解的IOC配置、注解改造CRUD(半xml半注解)、spring_junit(注解引入核心配置文件)

1、使用IOC完成CRUD 2、基于注解的IOC配置 3、使用注解改造CRUD(半xml半注解) 4、纯注解开发 5、spring与junit的整合 使用普通CRUD 项目 spring_day02_1_crud_normal a、引入依赖 <dependencies> <!--spring的核心包(基本)--> &...

Valentino112358的博客 296

Spring-day03(02)使用注解代替Xml配置

1.导入新的命名空间 将对象配置到容器 或 修改对象的作用范围 属性注入 对象类型注入 自动装配

qq_40967319的博客 165

DAY02_Spring—第三方资源配置管理&Spring容器&Spring注解开发&Spring整合Mybatis和Junit

Spring第三方资源配置管理、Spring容器、Spring注解开发、Spring整合Mybatis和Junit

m0_57075290的博客 1868
上一篇: spring_day01_入门&&IOC
下一篇: spring_day03_AOP
冰蓝心灵
博客等级 码龄10年 22粉丝 141原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值