spring创建对象




思考:spring的控制翻转其实就是将创建对象也就是实例化对象交给spring去做,当你在beans.xml中注册了一个bean时,spring已经帮你实例化好了,你只需要在用的时候从ApplicationContext中取出来即可。而我们在不用spring的时候都是什么时候使用对象的时候再去创建对象然后才能使用你所创建的对象,这样就是控制反转,将控制权交给spring容器。


取别名只是多了个名字



不同类型参数注入



各类型属性参数值注入练习

<bean id="address" class="com.kuang.pojo.Address"><property name="address" value="西安"></property></bean><bean id="student" class="com.kuang.pojo.Student"><property name="name" value="李天舒"></property><property name="address" ref="address"></property><property name="wife"><null/></property><property name="hobbys"><list><value>唱</value><value>跳</value><value>rap</value></list></property><property name="card"><map><entry key="身份证" value="14121512"></entry><entry key="饭卡" value="2165451"></entry></map></property><property name="games"><set><value>lol</value><value>bob</value><value>coc</value></set></property><property name="books"><array><value>三国演义</value><value>水浒传</value><value>西游记</value></array></property><property name="info"><props><prop key="url">url</prop><prop key="username">root</prop><prop key="password">123456</prop></props></property></bean>

c命名空间和p命名空间





ByType可以省略id名,因为ByType是根据对象属性类型来自动装配的




使用了@Autowired注解可以省略set方法

//关于@nullable注解
public void people(@nullable String name){this.name = name;
}
如果使用了@nullable注解标记了字段,那么这个字段可以值可以为null


注意点



这种情况personxml配置中aotuwired=“byname” 和 不填 都可以自动装配id为"dog119"的对象和id为"cat22"的对象

但是如果autowire=“byType” 就会报错,原因是xml文件中配置了多个对象,类型都相同,但是名字不同,xml按照类型去自动装配的话不知道应该装配哪个对象,就会报错

========================================================================================

使用注解开发


@Component


在实体类上加上@Component注解后就不用在beans.xml中注册这个bean了,但是没有id,在context.getBean(“XX”)方法中所填的id默认为类名小写


//此处getBean有两种方式:一种强转类型和一种不用转类型
1、User user = (User)context.getBean("user");
2、Object user = context.getBean("user",User.class);

@value


衍生注解


@Configuration和@bean

@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的<beans>,作用为:配置spring容器(应用上下文)package com.dsx.demo;import org.springframework.context.annotation.Configuration;@Configuration
public class TestConfiguration {public TestConfiguration() {......}
}

这个注解加在哪个类上,就相当于这个类变成了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" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsdhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsdhttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false"></beans>

再将@bean注解加在具体的一个类上,就相当于在这个xml文件中注册一个bean,而且这个类一定是返回pojo包下的某个实体类对象,比如


注意点:(1)@Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同;

举例:取得这个bean对象时,我们的id值使用的是getuser----->context.getBean(“getUser”)

(2)@Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域

(3)既然@Bean的作用是注册bean对象,那么完全可以使用@Component、@Controller、@Service、@Repository等注解注册bean(在需要注册的类上加注解),当然需要配置@ComponentScan注解进行自动扫描。


实体类

package com.kuang.pojo;import org.springframework.beans.factory.annotation.Value;public class User {private String name;private int age;public String getName() {return name;}@Value("Litianshu")public void setName(String name) {this.name = name;}public int getAge() {return age;}@Value("18")public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "User{" +"name='" + name + '\'' +", age=" + age +'}';}
}

配置类

package com.kuang.config;import com.kuang.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;@Configuration
@ComponentScan("com.kuang.pojo")
public class Config {@Beanpublic User getUser(){return new User();}
}

测试代码

import com.kuang.config.Config;
import com.kuang.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Test {@org.junit.Testpublic void test(){ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);User user = (User) context.getBean("getUser");System.out.println(user);}}

测试代码目录结构

动态代理AND AOP

方式一:使用spring的接口实现(MethodBeforeAdvice、AfterReturingAdvice两个接口)

主要是springAPI接口实现

方式二:使用自定义的类和方法作为切面和通知

主要是切面定义



注解实现aop

aop:在不影响原业务代码的基础上增强业务

注解aop测试代码

package com.kuang.aopdiy;import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
//切面类
@Aspect
public class Annotation {@Before("execution(* com.kuang.service.UserService.*(..))")public void before(){System.out.println("方法执行前~~~~~");}@After("execution(* com.kuang.service.UserService.*(..))")public void after(){System.out.println("方法执行后~~~~~");}}
         <!--切面类bean注册--><bean id="annotation" class="com.kuang.aopdiy.Annotation"></bean><!--注解aop支持开启--><aop:aspectj-autoproxy/>

使用aop需要一个aop织入依赖,如下

aspectjweaver是spring的切入点表达式需要用的包
<dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.4</version></dependency>

整合mybatis需要用到的依赖:


spring整合mybatis

spring配置数据源需要两个东西:一个是spring-jdbc的依赖,另一个就是该包下的DriverManagerDataSource类

第一步:配置数据源


遇到的问题:在spring中配置mybatis时由于全类名太长只能记住DriverManagerDataSource,而spring没有提示全类名,就需要去file—setting—plugin中搜索spring,将spring相关插件勾选上,再重启IDEA就可以看到提示了

第二部:配置sqlsessionFactory

在spring-mybatis中,创建sqlSessionFactory是使用sqlSessionFactoryBean这个对象,并在property中配置数据源,这样sqlsessionfatory便在spring中创建好了

sqlsessionfatory的bean注册中还可以做其他在mybatis配置文件中所做的事情,注册mapper;还可以绑定mybatis-config.xml文件,这样的话,spring和mybatis两个配置文件就联系起来了


第三步:注册sqlsession对象


在spring中sqlsession叫做sqlsessiontemplate,注册SqlSessionTemplate时需要将SqlSessionFactory作为SqlSessionTemplate的构造器参数注入,因为在创建SqlSessionTemplate对象时需要用到构造器,而SqlSessionTemplate没有无参构造器,也没有set方法,只能通过有参构造器的方式创建,而传入这个有参构造器的参数便是SqlSessionFactory,我们只需引入SqlSessionFactory即可

第四步:编写UserMapper实现类

要记得将这个实现类注册到spring中!并传入参数:sqlsessiontemplate


spring-mybatis整合demo代码

  • 项目结构:
  • mybatis配置文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings><setting name="logImpl" value="STDOUT_LOGGING"/></settings>
</configuration>
  • spring配置文件:
<?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"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.5.xsd"><bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"></property><property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;CharacterEncoding=utf-8"></property><property name="username" value="root"></property><property name="password" value="root"></property></bean><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="datasource"></property><!--绑定mybatis-config配置文件--><property name="configLocation" value="classpath:mybatis-config.xml"></property><!--将mybatis中的**mapper.xml文件的注册放在这里来做--><property name="mapperLocations" value="classpath:com/kuang/mapper/*.xml"></property></bean><bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"><constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg></bean><bean id="usermapper" class="com.kuang.mapper.UserMapperImpl"><property name="sqlSessionTemplate" ref="sqlSessionTemplate"></property></bean></beans>
  • UserMapper.class
package com.kuang.mapper;
import com.kuang.pojo.User;
import java.util.List;public interface UserMapper {public List<User> selectUser();
}
  • UserMapperImpl.class
package com.kuang.mapper;
import com.kuang.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;public class UserMapperImpl implements UserMapper{SqlSessionTemplate sqlSessionTemplate;public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {this.sqlSessionTemplate = sqlSessionTemplate;}public List<User> selectUser() {UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);return mapper.selectUser();}
}
  • UserMapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.mapper.UserMapper"><select id="selectUser" resultType="com.kuang.pojo.User">select * from mybatis.user</select>
</mapper>

在spring中获取sqlsession的第二种方式:

让UserMapperImpl类在实现UserMapper接口的同时继承SqlSessionDaoSupport类,类中有getSqlsession方法可以直接获取sqlsession

当然,继承了SqlSessionDaoSupport类的实现类也需要在spring中注册一个bean

spring事务



使用事务一定需要导入aspectjweaver包

spring-kuang相关推荐

  1. Spring、Mybatis整合Service优化思路,DAO层、Service层最终编码以及log4j日志的使用

    5. Spring.Mybatis整合Service层事务控制优化思路分析 # spring中处理事务的两种方式1. 编程式事务处理定义:通过在业务层中注入事务管理器对象,然后通过编码的方式进行事务控 ...

  2. (kuang)1、Spring 笔记

    官网:https://spring.io/projects/spring-framework#overview 官方下载地址:https://repo.spring.io/release/org/sp ...

  3. (kuang) Spring 笔记

    目录 9.代理模式 9.2 加深理解 9.3 动态代理都没动态代理 10. AOP 10.1 什么是AOP 10.2 AOP在Spring中的作用 10.3 使用Spring实现AOP 9.代理模式 ...

  4. 狂神说Spring讲解第19动态代理中错误java: 不兼容的类型: com.Orac.kuang.Host无法转换为com.kuang.demo3.Rent

    java: 不兼容的类型: com.Oracle.demo3.Host无法转换为com.Oracle.demo3.Rent 解决方法: Clinet: package com.Oracle.demo3 ...

  5. spring Bean自动装配

    spring Bean自动装配 自动装配是使用spring满足bean依赖的一种方式. spring会在应用上下文中为某个bean寻找其依赖的bean. spring自动装配需要从两个角度来实现,或者 ...

  6. spring IOC创建对象方式

    spring IOC创建对象方式 通过无参构造来创建 验证方法: 创建实体类: public class User {private String name;public User() {System ...

  7. 第一个spring程序

    第一个spring程序: 第一步:导入jar包. 新建maven项目: <dependency><groupId>org.springframework</groupId ...

  8. (Spring)声明式事务

    Spring中的事务管理 Spring在不同的事务管理API之上定义了一个抽象层,使得开发人员不必了解底层的事务管理API就可以使用Spring的事务管理机制.Spring支持编程式事务管理和声明式的 ...

  9. (Spring)自动装配bean

    文章目录 自动装配bean 1. 环境搭建 2. byName自动装配 3. byType自动装配 4. 使用注解自动装配 4.1 @Autowired和@Qualifier 4.2 @Resourc ...

  10. (Spring)Spring的使用

    文章目录 一.HelloSpring 二.IOC创建对象方式 2.1 无参构造创建 2.2 有参构造创建 三. Spring配置 3.1 别名alias 3.2 bean配置 3.3 import 一 ...

最新文章

  1. 分页插件php,文章内容分页插件
  2. 德鲁克《新企业》学习收获
  3. 陈杰院士:多无人系统协同中的人工智能安全探索
  4. 指针和数组的区别是什么?
  5. 注意2018年数据中心的这5大发展趋势
  6. stm32 IAP APP 相互跳转实验 (keil4 jlink STM32F407ZE
  7. linux python3安装教程_linux python3安装
  8. eosio.cdt心得
  9. oracle11g 安装在rhel5.0笔记
  10. Cisco——DHCPv6小实验
  11. 中位数和顺序统计,以线性期望时间做选择
  12. mysql 批量数据循环插入
  13. Windows 7 纯净版各版本下载
  14. 明华RD读卡器校验密码问题
  15. UCOS操作系统——创建与删除任务(三)
  16. Button按钮及其点击事件方式
  17. 计算机无法连接steam,无法连接至steam网络怎么办 无法连接至steam网络解决方法【图文】...
  18. 治疗便秘的30种秘方
  19. 计算机技术在生物工程方面的应用,信息技术下的生物工程应用论文
  20. 2011届移动开发者大会

热门文章

  1. openfeign调用异常:feign.FeignException: [405] during [GET]
  2. 【Visual C++】游戏开发笔记二十五 最简化的DirectX开发环境的配置
  3. SpringMVC整合Redis实战
  4. SpringMVC与Shiro快速整合
  5. PbS包覆钙钛矿量子点;PbS包覆CsPbI3量子点的透射电镜图和高分辨透射电子显微镜图像和光致发光光谱图齐岳生物
  6. 英语作文考前必背10大类万能句型
  7. mongodb中的read concern和write concern
  8. AJAX框架眼镜店活动,眼镜店节日促销H5的活动方案有哪些?快来看看吧!
  9. termux安装kodbox-方便简单图形界面操作
  10. python wifi模块