spring(二)
发布日期:2021-07-22 10:54:14 浏览次数:19 分类:技术文章

本文共 14587 字,大约阅读时间需要 48 分钟。

这里写目录标题

spring中ioc的常用注解

环境搭建

第一步:拷贝必备 jar 包到工程的 lib 目录

注意:在基于注解的配置中,我们还要多拷贝一个 aop 的 jar 包。如下图:
在这里插入图片描述

第二步:使用@Component 注解配置管理的资源

/*** 账户的业务层实现类* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/@Component("accountService")public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao; } }/*** 账户的持久层实现类* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/@Component("accountDao")public class AccountDaoImpl implements IAccountDao {
private DBAssit dbAssit; }

注意: 当我们使用注解注入时,set 方法不用写

第三步:创建 spring 的 xml 配置文件并开启对注解的支持

注意: 基于注解整合时,导入约束时需要多导入一个 context 名称空间下的约束。 由于我们使用了注解配置,此时不能在继承

JdbcDaoSupport,需要自己配置一个 JdbcTemplate

常用注解

1 用于创建对象的

相当于: <bean id ="" class"">
1.1 @Component

作用: 把资源让 spring 来管理。相当于在 xml 中配置一个 bean。 属性: value:指定 bean 的 id。如果不指定

value 属性,默认 bean 的 id 是当前类的类名。首字母小写

1.2 @Controller @Service @Repository

他们三个注解都是针对一个的衍生注解,他们的作用及属性都是一模一样的;只不过是提供了更加明确的语义化

@Controller:一般用于表现层的注解。 @Service:一般用于业务层的注解。 @Repository:一般用于持久层的注解。
细节:如果注解中有且只有一个属性要赋值时,且名称是 value,value 在赋值是可以不写

2 用于注入数据的

相当于:

2.1 @Autowired

作用: 自动按照类型注入。当使用注解注入属性时,set 方法可以省略。它只能注入其他 bean类型。当有多个类型匹配时,使用要注入的对象变量名称作为 bean 的 id,在 spring 容器查找,找到了也可注入成功;找不到则报错

2.2 @Qualifier

作用: 在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和@Autowire一起使用;但是给方法参数注入时,可以独立使用

属性: value:指定 bean 的 id

2.3 @Resource

作用: 直接按照 Bean 的 id 注入。它也只能注入其他 bean 类型

属性: name:指定 bean 的 id

2.4 @Value

作用: 注入基本数据类型和 String 类型数据的

属性: value:用于指定值
它可以使用spring中的spEL写法(也就是spring的el表达式)
spEL的写法:${表达式}

3 用于改变作用范围的:

相当于:<bean id="" class="" scope="">
@Scope

作用: 指定 bean 的作用范围

属性: value:指定范围的值
取值:singleton prototype request session globalsession

4 和生命周期相关的:(了解)

相当于:<bean id="" class="" init-method="" destroy-method="" />
4.1 @PostConstruct

作用: 用于指定初始化方法

4.2 @PreDestroy

作用: 用于指定销毁方法

5 关于 Spring 注解和 XML 的选择问题

注解的优势:
配置简单,维护方便(我们找到类,就相当于找到了对应的配置)。
XML 的优势:
修改时,不用改源码。不涉及重新编译和部署。
Spring 管理 Bean 方式的比较:

spring 管理对象细节

基于注解的 spring IoC 配置中,bean 对象的特点和基于 XML 配置是一模一样的。

spring 的纯注解配置

1 待改造的问题

我们发现,之所以我们现在离不开 xml 配置文件,是因为我们有一句很关键的配置:

如果他要也能用注解配置,那么我们就离脱离 xml 文件又进了一步。另外,数据源和 JdbcTemplate 的配置也需要靠注解来实现。

2 新注解说明

2.1 @Configuration

作用: 用于指定当前类是一个 spring配置类,当创建容器时会从该类上加载注解。获取容器时需要使用AnnotationApplicationContext(有@Configuration注解的类.class)

属性: value:用于指定配置类的字节码
细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注释可以不写

示例代码:

/*** spring 的配置类,相当于 bean.xml 文件* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/@Configurationpublic class SpringConfiguration {
}

2.2 @ComponentScan

作用: 用于指定 spring 在初始化容器时要扫描的包。作用和在 spring 的 xml配置文件中的:<context:component-scan base-package=“com.itheima”/>是一样的

属性:basePackages:用于指定要扫描的包。和该注解中的 value 属性作用一样

示例代码:

/*** spring 的配置类,相当于 bean.xml 文件* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/@Configuration@ComponentScan("com.itheima")public class SpringConfiguration {
}

2.3 @Bean

作用: 该注解只能写在方法上,表明使用此方法创建一个对象,并且放入 spring 容器

属性: name:给当前@Bean注解方法创建的对象指定一个名称(即 bean 的 id)

示例代码:

/*** 连接数据库的配置类* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/public class JdbcConfig {
/*** 创建一个数据源,并存入 spring 容器中* @return*/@Bean(name="dataSource")public DataSource createDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();ds.setUser("root");ds.setPassword("1234");ds.setDriverClass("com.mysql.jdbc.Driver");ds.setJdbcUrl("jdbc:mysql:///spring_day02");return ds;} catch (Exception e) {
throw new RuntimeException(e);} }/*** 创建一个 DBAssit,并且也存入 spring 容器中* @param dataSource* @return*/@Bean(name="dbAssit")public DBAssit createDBAssit(DataSource dataSource) {
return new DBAssit(dataSource);} }

2.4 @PropertySource

作用: 用于加载.properties 文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到properties配置文件中,就可以使用此注解指定 properties 配置文件的位置

属性: value[ ]:用于指定 properties文件位置。如果是在类路径下,需要写上 classpath

示例代码:

配置:

/*** 连接数据库的配置类* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/public class JdbcConfig {
@Value("${jdbc.driver}")private String driver;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;/*** 创建一个数据源,并存入 spring 容器中* @return*/@Bean(name="dataSource")public DataSource createDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();ds.setDriverClass(driver);ds.setJdbcUrl(url);ds.setUser(username);ds.setPassword(password);return ds;} catch (Exception e) {
throw new RuntimeException(e);} } }jdbc.properties 文件:jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/day44_ee247_springjdbc.username=rootjdbc.password=1234

2.5 @Import

作用: 用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration 注解。当然,写上也没问题

属性:value[ ]:用于指定其他配置类的字节码

示例代码:

@Configuration@ComponentScan(basePackages = "com.itheima.spring") @Import({
JdbcConfig.class})public class SpringConfiguration {
}@Configuration@PropertySource("classpath:jdbc.properties")public class JdbcConfig{
}

2.6 通过注解获取容器:

ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);

案例使用xml方式和注解方式实现单表的CRUD操作

持久层技术选择:dbutils

环境搭建

1 拷贝 jar 包

2 创建数据库和编写实体类

create table account(id int primary key auto_increment,name varchar(40),money float)character set utf8 collate utf8_general_ci;insert into account(name,money) values('aaa',1000);insert into account(name,money) values('bbb',1000);insert into account(name,money) values('ccc',1000);
/*** 账户的实体类* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/public class Account implements Serializable {
private Integer id;private String name;private Float money;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; }public Float getMoney() {
return money; }public void setMoney(Float money) {
this.money = money; } }

3 编写持久层代码

/*** 账户的持久层接口* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/public interface IAccountDao {
/*** 保存* @param account*/void save(Account account);/*** 更新* @param account*/void update(Account account);/*** 删除* @param accountId*/void delete(Integer accountId);/*** 根据 id 查询* @param accountId* @return*/Account findById(Integer accountId);/*** 查询所有* @return*/List
findAll();}/*** 账户的持久层实现类* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/public class AccountDaoImpl implements IAccountDao {
private DBAssit dbAssit;public void setDbAssit(DBAssit dbAssit) {
this.dbAssit = dbAssit; }@Overridepublic void save(Account account) {
dbAssit.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());}@Overridepublic void update(Account account) {
dbAssit.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());}@Overridepublic void delete(Integer accountId) {
dbAssit.update("delete from account where id=?",accountId);}@Overridepublic Account findById(Integer accountId) {
return dbAssit.query("select * from account where id=?",newBeanHandler
(Account.class),accountId);}@Overridepublic List
findAll() {
return dbAssit.query("select * from account where id=?",newBeanListHandler
(Account.class));} }

4 编写业务层代码

/*** 账户的业务层接口* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/public interface IAccountService {
/*** 保存账户* @param account*/void saveAccount(Account account);/*** 更新账户* @param account*/void updateAccount(Account account);/*** 删除账户* @param account*/void deleteAccount(Integer accountId);/*** 根据 id 查询账户* @param accountId* @return*/Account findAccountById(Integer accountId);/*** 查询所有账户* @return*/List
findAllAccount();}/*** 账户的业务层实现类* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao; }@Overridepublic void saveAccount(Account account) {
accountDao.save(account);}@Overridepublic void updateAccount(Account account) {
accountDao.update(account);}@Overridepublic void deleteAccount(Integer accountId) {
accountDao.delete(accountId);}@Overridepublic Account findAccountById(Integer accountId) {
return accountDao.findById(accountId);}@Overridepublic List
findAllAccount() {
return accountDao.findAll();} }

5 创建并编写配置文件

配置步骤

配置对象

测试案例

1 测试类代码

/*** 测试类* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/public class AccountServiceTest {
/*** 测试保存*/@Testpublic void testSaveAccount() {
Account account = new Account();account.setName("黑马程序员");account.setMoney(100000f);ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");IAccountService as = ac.getBean("accountService",IAccountService.class);as.saveAccount(account);}/*** 测试查询一个*/@Testpublic void testFindAccountById() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");IAccountService as = ac.getBean("accountService",IAccountService.class);Account account = as.findAccountById(1);System.out.println(account);}/*** 测试更新*/@Testpublic void testUpdateAccount() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");IAccountService as = ac.getBean("accountService",IAccountService.class);Account account = as.findAccountById(1);account.setMoney(20301050f);as.updateAccount(account);}/*** 测试删除*/@Testpublic void testDeleteAccount() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");IAccountService as = ac.getBean("accountService",IAccountService.class);as.deleteAccount(1);}/*** 测试查询所有*/@Testpublic void testFindAllAccount() {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");IAccountService as = ac.getBean("accountService",IAccountService.class);List
list = as.findAllAccount();for(Account account : list) {
System.out.println(account);} } }

改造基于注解的ioc案例,使用纯注解的方式实现

spring的新注解使用

1 @Configuration

作用: 用于指定当前类是一个 spring配置类,当创建容器时会从该类上加载注解。获取容器时需要使用AnnotationApplicationContext(有@Configuration注解的类.class)

属性: value:用于指定配置类的字节码

细节:当配置AnnotationConfigApplicationContext对象创建的参数时,可以不写

示例代码:

/*** spring 的配置类,相当于 bean.xml 文件* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/@Configurationpublic class SpringConfiguration {
}

2 @ComponentScan

作用: 用于指定 spring 在初始化容器时要扫描的包。作用和在 spring 的 xml 配置文件中的:<context:component-scan base-package=“com.itheima”/>是一样的

属性: basePackages:用于指定要扫描的包。和该注解中的 value 属性作用一样

示例代码:

/*** spring 的配置类,相当于 bean.xml 文件* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/@Configuration@ComponentScan("com.itheima")public class SpringConfiguration {
}

3 @Bean

作用: 该注解只能写在方法上,表明使用此方法创建一个对象,并且放入 spring 容器

属性: name:给当前@Bean 注解方法创建的对象指定一个名称(即 bean 的 id) 默认值是当前方法的名称·

细节:当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象
查找方式跟和Autowired注解的作用是一样的

示例代码:

/*** 连接数据库的配置类* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/public class JdbcConfig {
/*** 创建一个数据源,并存入 spring 容器中* @return*/@Bean(name="dataSource")public DataSource createDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();ds.setUser("root");ds.setPassword("1234");ds.setDriverClass("com.mysql.jdbc.Driver");ds.setJdbcUrl("jdbc:mysql:///spring_day02");return ds;} catch (Exception e) {
throw new RuntimeException(e);} }/*** 创建一个 DBAssit,并且也存入 spring 容器中* @param dataSource* @return*/@Bean(name="dbAssit")public DBAssit createDBAssit(DataSource dataSource) {
return new DBAssit(dataSource);} }

4 @PropertySource

作用: 用于加载.properties 文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到properties配置文件中,就可以使用此注解指定 properties 配置文件的位置

属性: value[]:用于指定 properties 文件位置。如果是在类路径下,需要写上 classpath:

示例代码:

配置:/*** 连接数据库的配置类* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/public class JdbcConfig {
@Value("${jdbc.driver}")private String driver;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;/*** 创建一个数据源,并存入 spring 容器中* @return*/@Bean(name="dataSource")public DataSource createDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();ds.setDriverClass(driver);ds.setJdbcUrl(url);ds.setUser(username);ds.setPassword(password);return ds;} catch (Exception e) {
throw new RuntimeException(e);} } }

jdbc.properties 文件: jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/day44_ee247_spring
jdbc.username=root
jdbc.password=1234

5 @Import

作用: 用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration 注解。当然,写上也没问题

属性: value[]:用于指定其他配置类的字节码
当我们使用import的注解之后,有import注解的类就是父配置类,而导入的都是子配置类

示例代码:

@Configuration@ComponentScan(basePackages = "com.itheima.spring") @Import({
JdbcConfig.class})public class SpringConfiguration {
}@Configuration@PropertySource("classpath:jdbc.properties")public class JdbcConfig{
}

6 通过注解获取容器:

ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);

spring和Junit整合

配置步骤

第一步:拷贝整合 junit 的必备 jar 包到 lib 目录

此处需要注意的是,导入 jar 包时,需要导入一个 spring 中 aop 的 jar 包

第二步:使用@RunWith 注解替换原有运行器

/*** 测试类* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/@RunWith(SpringJUnit4ClassRunner.class)public class AccountServiceTest {
}

3 第三步:使用@ContextConfiguration 指定 spring 配置文件的位置

/*** 测试类* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations= {
"classpath:bean.xml"})public class AccountServiceTest {
}

@ContextConfiguration 注解:

locations 属性:用于指定配置文件的位置。如果是类路径下,需要用classpath:表明
classes 属性:用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置

第四步:使用@Autowired 给测试类中的变量注入数据

/*** 测试类* @author 黑马程序员* @Company http://www.ithiema.com* @Version 1.0*/@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations= {
"classpath:bean.xml"})public class AccountServiceTest {
@Autowiredprivate IAccountService as ; }

测试类可以配到 XML 中

为什么不采用配置到 xml 中的方式?
第一:当我们在 xml 中配置了一个 bean,spring加载配置文件创建容器时,就会创建对象
第二:测试类只是我们在测试功能时使用,而在项目中它并不参与程序逻辑,也不会解决需求上的问题,所以创建完了,并没有使用。那么存在容器中就会造成资源的浪费

1、应用程序的入口

main方法
2、junit单元测试中,没有main方法也能执行
junit集成了一个main方法
该方法就会判断当前测试类中哪些方法有 @Test注解
junit就让有Test注解的方法执行
3、junit不会管我们是否采用spring框架
在执行测试方法时,junit根本不知道我们是不是使用了spring框架
所以也就不会为我们读取配置文件/配置类创建spring核心容器
4、由以上三点可知
当测试方法执行时,没有Ioc容器,就算写了Autowired注解,也无法实现注入

转载地址:https://blog.csdn.net/m0_56426304/article/details/118060338 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:lambda表达式:
下一篇:Spring(一)

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月03日 16时04分28秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章

武田中国创新挑战赛重磅启动,诚邀初创企业共赴数字医疗之途 2019-04-25
九巨龙集团安全大检查行动,践行“客户满意工程”牢筑安全防线! 2019-04-25
最好吃的8款粽子,看看有没有你家乡的! 2019-04-25
端午前后湿热当道,这些祛湿的好方法一定要收好 2019-04-25
最好吃的8款粽子,看看有没有你家乡的! 2019-04-25
端午前后湿热当道,这些祛湿的好方法一定要收好 2019-04-25
九巨龙集团被授予“2020年全市疫情防控慈善捐助企业楷模” 2019-04-25
清徐老陈醋签约盒马与数字乡村特色新品战略合作 2019-04-25
视听·封报丨5G发展带来哪些改变?“虚拟偶像”成为追星新潮流 2019-04-25
最好吃的8款粽子,看看有没有你家乡的! 2019-04-25
第10届上海尚品家居展实力来袭,优质生产型企业加持核心优势 2019-04-25
丁磊:高合汽车下个月交付过千,刷新纪录 2019-04-25
2021乌拉盖旅游推介会暨“爱上草原”云平台发布仪式 2019-04-25
博仲兴业力作——《爱的雨季》讲述爱情的奥秘 2019-04-25
墨斗互动公益助力山西大学 毕业季,青春无畏,逐梦扬威 2019-04-25
中品丝路:在重要场所讲好中国品牌故事 2019-04-25
夏日狂欢 — BODY JAZZ两周年庆典———若水,以柔见世界 2019-04-25
京东品牌联盟:618品牌狂欢盛典-品宣销售再创历史新高 2019-04-25
五色新丝缠角粽 粽享孝养温情|九巨龙孝养城带您粽情一夏 2019-04-25
九巨龙这两学校竟麦浪滚滚!太美!太用心! 2019-04-25