
Java后端的学习之Spring基础
如果要学习spring
,那么什么是框架,spring
又是什么呢?学习spring
中的ioc
和bean
,以及aop
,IOC
,Bean
,AOP
,(配置,注解,api
)-springFramework

各种学习的知识点:
spring expression language
spring integration
spring web flow
spring security
spring data
spring batch
spring
网站:
http://spring.io/

http://spring.io/projects/spring-framework

spring
是一种开源框架,是为了解决企业应用开发的复杂性问题而创建的,现在的发展已经不止于用于企业应用了.
spring
是一种轻量级的控制反转(IoC)和面向切面(AOP)的容器框架.
一句名言:spring
带来了复杂的javaee
开发的春天.
jdbc orm
oxm jms
transactions
websocket servlet
web portlet
aop aspects instrumentation messaging
beans core context spel
springmvc+spring+hibernate/ibatis
->企业应用
什么是框架,为什么要用框架:
什么是框架:


框架就是别人制定好的一套规则和规范,大家在这个规范或者规则下进行工作,可以说,别人盖好了楼,让我们住.


软件框架是一种半成品,具有特定的处理流程和控制逻辑,成熟的,可以不断升级和改进的软件.
使用框架重用度高,开发效率和质量的提高,容易上手,快速解决问题.
spring ioc
容器

接口,是用于沟通的中介物的,具有抽象化,java
中的接口,就是声明了哪些方法是对外公开的.
面向接口编程,是用于隐藏具体实现的组件.
案例:
// 声明一个接口
public interface DemoInterface{
String hello(String text);
// 一个hello方法,接收一个字符串型的参数,返回一个`String`类型.
}
// 实现
public class OneInterface implements DemoInterface{
@Override
public String hello(String text){
return "你好啊: " + text;
}
}
// 测试类
public class Main{
public static void main(String[] args){
DemoInterface demo = new OneInterface();
System.out.println(demo.hello("dashucoding");
}
}
什么是IOC
,IOC
是控制反转,那么什么控制反转,控制权的转移,应用程序不负责依赖对象的创建和维护,而是由外部容器负责创建和维护.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="oneInterface" class="com.ioc.interfaces.OneInterfaceImpl"></bean>
</beans>
spring.xml
测试:
import org.junit.Test;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestOneInterface extends UnitTestBase {
public TestOneInterface(){
super("spring.xml");
}
@Test
public void testHello(){
OneInterface oneInterface = super.getBean("oneInterface");
System.out.println(oneInterface.hello("dashucoding"));
}
}
单元测试
下载一个包junit-*.jar
导入项目中,然后创建一个UnitTestBase
类,用于对spring
进行配置文件的加载和销毁,所有的单元测试都是继承UnitTestBase
的,然后通过它的getBean
方法获取想要的对象,子类要加注解@RunWith(BlockJUnit4ClassRunner.class)
,单元测试方法加注解@Test
.
public ClassPathXmlApplicationContext context;
public String springXmlpath;
public UnitTestBase(){}
public UnitTestBase(String springXmlpath){
this.springXmlpath = springXmlpath;
}
@Before
public void before(){
if(StringUtils.isEmpty(springXmlpath)){
springXmlpath = "classpath*:spring-*.xml";
}
try{
context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+"));
context.start();
}catch(BeansException e){
e.printStackTrace();
}
}
@After
public void after(){
context.destroy();
}
@SuppressWarnings("unchecked")
protected <T extends Object> T getBean(String beanId){
return (T)context.getBean(beanId);
}
protected <T extends Object> T getBean(Class<T> clazz){
return context.getBean(clazz);
}
}
bean
容器:
org.springframework.beans
和org.springframework.context
BeanFactory
提供配置结构和基本功能,加载并初始化Bean
,ApplicationContext
保存了Bean
对象.
// 文件
FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("D:/appcontext.xml");
// Classpath
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-context.xml");
// Web应用
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
spring
注入:启动spring
加载bean
的时候,完成对变量赋值的行为.注入方式:设值注入和构造注入.
// 设值注入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="iService" class="com.service.iServiceImpl">
<property name="iDAO" ref="DAO"/>
</bean>
<bean id="DAO" class="com.iDAOImpl"></bean>
</beans>
// 构造注入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="iService" class="com.service.iServiceImpl">
<constructor-arg name="DAO" ref="DAO"/>
<property name="injectionDAO" ref="injectionDAO"></property>
</bean>
<bean id="DAO" class="com.iDAOImpl"></bean>
</beans>
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="injectionService" class="com.injection.service.InjectionServiceImpl"></bean>
<bean id="injectionDAO" class="com.ijection.dao.InjectionDAOImpl"></bean>
</beans>
// 接口-业务逻辑
public interface InjectionService {
public void save(String arg);
}
// 实现类-处理业务逻辑
public class InjectionServiceImpl implements InjecionService {
private InjectionDAO injectionDAO;
public InjectionServiceImpl(InjectionDAO injectionDAO) {
this.injectionDAO = injectionDAO;
}
public void setInjectionDAO(InjectiionDAO injectionDAO) {
this.injectionDAO = injectionDAO;
}
public void save(String arg) {
System.out.println("接收" + arg);
arg = arg + ":" + this.hashCode();
injectionDAO.save(arg);
}
}
// 接口-数据库-调用DAO
public interface InjectionDAO {
// 声明一个方法
public void save(String arg);
}
// 实现类
public class InjectionDAOImpl implements InjectionDAO {
// 实现接口中的方法
public void save(String arg) {
System.out.println("保存数据" + arg);
}
}
// 测试
import org.junit.Test;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestInjection extends UnitTestBase {
public TestInjection(){
super("classpath:spring-injection.xml");
}
@Test
public void testSetter(){
InjectionService service = super.getBean("injectionService");
service.save("保存的数据");
}
@Test
public void testCons() {
InjectionService service = super.getBean("injectionService");
service.save("保存的数据");
}
}
bean
的配置:
id:id是整个ioc容器中,bean的标识
class:具体要实例化的类
scope:作用域
constructor arguments:构造器的参数
properties:属性
autowiring mode:自动装配的模式
lazy-initialization mode:懒加载模式
Initialization/destruction method:初始化和销毁的方法
作用域
singleton:单例
prototype:每次请求都创建新的实例
request:每次http请求都创建一个实例有且当前有效
session:同上
spring bean
配置之Aware
接口:spring
中提供了以Aware
结尾的接口,为spring
的扩展提供了方便.
bean
的自动装配autowiring
no是指不做任何操作
byname是根据自己的属性名自动装配
byType是指与指定属性类型相同的bean进行自动装配,如果有过个类型存在的bean,那么就会抛出异常,不能使用byType方式进行自动装配,如果没有找到,就不什么事都不会发生
Constructor是与byType类似,它是用于构造器参数的,如果没有找到与构造器参数类型一致的bean就会抛出异常
spring bean
配置的resource
resources:
urlresource是url的资源
classpathresource是获取类路径下的资源
filesystemresource是获取文件系统的资源
servletcontextresource是servletcontext封装的资源
inputstreamresource是针对输入流封装的资源
bytearrayresource是针对字节数组封装的资源
public interface ResourceLoader{
Resource getResource(String location);
}
ResourceLoader
classpath: Loaded from the classpath;
file: Loaded as a URL, from the filesystem;
http: Loaded as a URL;
案例:
public class MResource implements ApplicationContextAware{
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void resource(){
Resource resource = applicationContext.getResource("classpath:config.txt");
System.out.println(resource.getFilename());
}
}
// 单元测试类
import com.test.base.UnitTestBase;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestResource extends UnitTestBase {
public TestResource() {
super("classpath:spring-resource.xml");
}
@Test
public void testResource() {
MResource resource = super.getBean("mResource");
try{
resource.resource();
}catch(IOException e){
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="moocResource" class="com.resource.MResource"></bean>
</beans>
bean
的定义与学习:
<context:annotation-config/>
@Component,@Repository,@Service,@Controller
@Required,@Autowired,@Qualifier,@Resource
@Configuration,@Bean,@Import,@DependsOn
@Component,@Repository,@Service,@Controller
-
@Repository
用于注解DAO
类为持久层 -
@Service
用于注解Service
类为服务层 -
@Controller
用于Controller
类为控制层
元注解Meta-annotations
是spring
提供的注解可以作为字节的代码叫元数据注解,处理value()
,元注解可以有其他的属性.
spring
可以自动检测和注册bean
@Service
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Autowired
public SimpleMovieLister(MovieFinder movieFinder){
this.movieFinder = movieFinder;
}
}
@Repository
public class JpaMovieFinder implements MovieFinder {
}
类的自动检测以及
Bean
的注册
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<context:component-scan base-package="org.example"/>
</beans>
类被自动发现并注册
bean
的条件:
用@Component,@Repository,@Service,@Controller注解或者使用@Component的自定义注解
@Required
用于bean
属性的setter
方法
@Autowired
注解
private MovieFinder movieFinder;
@Autowired
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
用于构造器或成员变量
@Autowired
private MovieCatalog movieCatalog;
private CustomePreferenceDap customerPreferenceDao;
@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}
@Autowired
注解
使用这个注解,如果找不到bean
将会导致抛出异常,可以使用下面代码避免,每个类只能有一个构造器被标记为required=true
.
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Autowired(required=false)
public void setMovieFinder(MovieFinder movieFinder){
this.movieFinder = movieFinder;
}
}
spring
是一个开源框架,spring是用j2ee开发的mvc框架,spring boot呢就是一个能整合组件的快速开发框架,因为使用maven管理,所以很便利。至于spring cloud,就是微服务框架了。
spring
是一个轻量级的Java
开发框架,是为了解决企业应用开发的复杂性而创建的框架,框架具有分层架构的优势.
spring
这种框架是简单性的,可测试性的和松耦合的,spring
框架,我们主要是学习控制反转IOC
和面向切面AOP
.
// 知识点
spring ioc
spring aop
spring orm
spring mvc
spring webservice
spring transactions
spring jms
spring data
spring cache
spring boot
spring security
spring schedule
spring ioc
为控制反转,控制反向,控制倒置,



Spring
容器是 Spring
框架的核心。spring
容器实现了相互依赖对象的创建,协调工作,对象只要关系业务逻辑本身,IOC
最重要的是完成了对象的创建和依赖的管理注入等,控制反转就是将代码里面需要实现的对象创建,依赖的代码,反转给了容器,这就需要创建一个容器,用来让容器知道创建对象与对象的关系.(告诉spring你是个什么东西,你需要什么东西)
xml,properties等用来描述对象与对象间的关系
classpath,filesystem,servletContext等用来描述对象关系的文件放在哪里了.
控制反转就是将对象之间的依赖关系交给了容器管理,本来是由应用程序管理的对象之间的依赖的关系.
spring ioc
体系结构
BeanFactory
BeanDefinition
spring ioc
是spring
的核心之一,也是spring体系的基础,在
spring中主要用户管理容器中的
bean.
spring的
IOC容器主要使用
DI方式实现的.
BeanFactory是典型的工厂模式,
ioc容器为开发者管理对象间的依赖关系提供了很多便利.在使用对象时,要
new object()来完成合作.
ioc:
spring容器是来实现这些相互依赖对象的创建和协调工作的.(由
spring`来复杂控制对象的生命周期和对象间的)
所有的类的创建和销毁都是由spring
来控制,不再是由引用它的对象了,控制对象的生命周期在spring
.所有对象都被spring
控制.
ioc
容器的接口(自己设计和面对每个环节):
BeanFactory
工厂模式
public interface BeanFactory {
String FACTORY_BEAN_PREFIX = "&";
Object getBean(String name) throws BeansException;
Object getBean(String name, Class requiredType) throws BeansException;
boolean containsBean(String name);
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
Class getType(String name) throws NoSuchBeanDefinitionException;
String[] getAliases(String name);
}
BeanFactory
三个子类:ListableBeanFactory
,HierarchicalBeanFactory
和AutowireCapableBeanFactory
,实现类是DefaultListableBeanFactory
.
控制反转就是所有的对象都被spring
控制.ioc
动态的向某个对象提供它所需要的对象.通过DI
依赖注入来实现的.如何实现依赖注入ID
,在Java
中有一特性为反射,它可以在程序运行的时候进行动态的生成对象和执行对象的方法,改变对象的属性.
public static void main(String[] args){
ApplicationContext context = new FileSystemXmlApplicationContext("applicationContext.xml");
Animal animal = (Animal)context.getBean("animal");
animal.say();
}
// applicationContext.xml
<bean id="animal" class="com.test.Cat">
<property name="name" value="dashu"/>
</bean>
public class Cat implements Animal {
private String name;
public void say(){
System.out.println("dashu");
}
public void setName(String name){
this.name = name;
}
}
public interface Animal {
public void say();
}
// bean
private String id;
private String type;
private Map<String,Object> properties=new HashMap<String, Object>();
<bean id="test" class="Test">
<property name="testMap">
</property>
</bean>
public static Object newInstance(String className) {
Class<?> cls = null;
Object obj = null;
try {
cls = Class.forName(className);
obj = cls.newInstance();
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
return obj;
}
核心是控制反转(
IOC
)和面向切面(AOP
),spring
是一个分层的JavaSE/EE
的轻量级开源框架.
web
:
struts,spring-mvc
service
:
spring
dao
:
mybatis,hibernate,jdbcTemplate,springdata
spring
体系结构
ioc
// 接口
public interface UserService {
public void addUser();
}
// 实现类
public class UserServiceImpl implements UserService {
@Override
public void addUser(){
System.out.println("dashucoding");
}
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="userServiceId" class="com.dashucoding.UserServiceImpl"></bean>
</beans>
测试:
@Test
public void demo(){
String xmlPath = "com/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserService userService = (UserService) applicationContext.getBean("userServiceId");
userService.addUser();
}
依赖注入:
class DemoServiceImpl{
private daDao daDao;
}
创建
service
实例,创建dao
实例,将dao
设置给service
.
接口和实现类:
public interface BookDao {
public void addBook();
}
public class BookDaoImpl implements BookDao {
@Override
public void addBook() {
System.out.println("dashucoding");
}
}
public interface BookService {
public abstract void addBook();
}
public class BookServiceImpl implements BookService {
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
@Override
public void addBook(){
this.bookDao.addBook();
}
}
配置文件:
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="bookServiceId" class="com.BookServiceImpl">
<property name="bookDao" ref="bookDaoId"></property>
</bean>
<bean id="bookDaoId" class="com.BookDaoImpl"></bean>
</beans>
测试:
@Test
public void demo(){
String xmlPath = "com/beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
BookService bookService = (BookService) applicationContext.getBean("bookServiceId");
bookService.addBook();
}
IDE
建立Spring
项目
File—>new—>project—>Spring
spring
// Server.java
public class Server {
privete String name;
public void setName(String name){
this.name = name;
}
public void putName(){
System.out.println(name);
}
}
// Main.java
public class Main{
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
Server hello = (Server)context.getBean("example_one");
hello.putName();
}
}
spring-config.xml
:
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="example_one" class="Server">
<property name="name" value="达叔小生"></property>
</bean>
</beans>
达叔小生:往后余生,唯独有你
You and me, we are family !
90后帅气小伙,良好的开发习惯;独立思考的能力;主动并且善于沟通
简书博客: 达叔小生
https://www.jianshu.com/u/c785ece603d1
结语
- 下面我将继续对 其他知识 深入讲解 ,有兴趣可以继续关注
- 小礼物走一走 or 点赞
网友评论