如果要学习spring,那么什么是框架,spring又是什么呢?学习spring中的ioc和bean,以及aop,IOC,Bean,AOP,(配置,注解,api)-springFramework.
各种学习的知识点:
springexpression languagespringintegrationspringweb flowspringsecurityspringdataspringbatch
spring网站:
http://spring.io/
http://spring.io/projects/spring-framework
spring是一种开源框架,是为了解决企业应用开发的复杂性问题而创建的,现在的发展已经不止于用于企业应用了.
spring是一种轻量级的控制反转(IoC)和面向切面(AOP)的容器框架.
一句名言:spring带来了复杂的javaee开发的春天.
jdbcormoxm jmstransactionswebsocket servletweb portletaop aspects instrumentation messagingbeans core context spel
springmvc+spring+hibernate/ibatis->企业应用
什么是框架,为什么要用框架:
什么是框架:
框架就是别人制定好的一套规则和规范,大家在这个规范或者规则下进行工作,可以说,别人盖好了楼,让我们住.
软件框架是一种半成品,具有特定的处理流程和控制逻辑,成熟的,可以不断升级和改进的软件.
使用框架重用度高,开发效率和质量的提高,容易上手,快速解决问题.
spring ioc容器
接口,是用于沟通的中介物的,具有抽象化,java中的接口,就是声明了哪些方法是对外公开的.
面向接口编程,是用于隐藏具体实现的组件.
案例:
// 声明一个接口publicinterfaceDemoInterface{Stringhello(String text);// 一个hello方法,接收一个字符串型的参数,返回一个`String`类型.}// 实现publicclassOneInterfaceimplementsDemoInterface{@OverridepublicStringhello(String text){return"你好啊: "+ text; }}// 测试类publicclassMain{publicstaticvoidmain(String[] args){ DemoInterface demo =newOneInterface(); System.out.println(demo.hello("dashucoding"); }}
什么是IOC,IOC是控制反转,那么什么控制反转,控制权的转移,应用程序不负责依赖对象的创建和维护,而是由外部容器负责创建和维护.
http://www.springframework.org/schema/beans/spring-beans.xsd">
spring.xml
测试:
importorg.junit.Test;@RunWith(BlockJUnit4ClassRunner.class)publicclassTestOneInterfaceextendsUnitTestBase{ publicTestOneInterface(){super("spring.xml"); }@Testpublic void testHello(){OneInterfaceoneInterface =super.getBean("oneInterface");System.out.println(oneInterface.hello("dashucoding")); }}
单元测试
下载一个包junit-*.jar导入项目中,然后创建一个UnitTestBase类,用于对spring进行配置文件的加载和销毁,所有的单元测试都是继承UnitTestBase的,然后通过它的getBean方法获取想要的对象,子类要加注解@RunWith(BlockJUnit4ClassRunner.class),单元测试方法加注解@Test.
publicClassPathXmlApplicationContext context;publicString springXmlpath;publicUnitTestBase(){}publicUnitTestBase(String springXmlpath){this.springXmlpath = springXmlpath; }@Beforepublicvoidbefore(){if(StringUtils.isEmpty(springXmlpath)){ springXmlpath ="classpath*:spring-*.xml"; }try{ context =newClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+")); context.start(); }catch(BeansException e){ e.printStackTrace(); } }@Afterpublicvoidafter(){ context.destroy(); }@SuppressWarnings("unchecked")protectedTgetBean(String beanId){return(T)context.getBean(beanId); }protectedTgetBean(Class
bean容器:
org.springframework.beans和org.springframework.context
BeanFactory提供配置结构和基本功能,加载并初始化Bean,ApplicationContext保存了Bean对象.
// 文件FileSystemXmlApplicationContext context =newFileSystemXmlApplicationContext("D:/appcontext.xml");// ClasspathClassPathXmlApplicationContext context =newClassPathXmlApplicationContext("classpath:spring-context.xml");// Web应用 org.springframework.web.context.ContextLoaderListener context org.springframework.web.context.ContextLoaderServlet 1
spring注入:启动spring加载bean的时候,完成对变量赋值的行为.注入方式:设值注入和构造注入.
// 设值注入
http://www.springframework.org/schema/beans/spring-beans.xsd">
// 构造注入
http://www.springframework.org/schema/beans/spring-beans.xsd">
spring注入:
http://www.springframework.org/schema/beans/spring-beans.xsd">
// 接口-业务逻辑publicinterfaceInjectionService{publicvoidsave(String arg);}
// 实现类-处理业务逻辑publicclassInjectionServiceImplimplementsInjecionService{privateInjectionDAO injectionDAO;publicInjectionServiceImpl(InjectionDAO injectionDAO){this.injectionDAO = injectionDAO; }publicvoidsetInjectionDAO(InjectiionDAO injectionDAO){this.injectionDAO = injectionDAO; }publicvoidsave(String arg){ System.out.println("接收"+ arg); arg = arg +":"+this.hashCode(); injectionDAO.save(arg); }}
// 接口-数据库-调用DAOpublicinterfaceInjectionDAO{// 声明一个方法publicvoidsave(String arg);}
// 实现类publicclassInjectionDAOImplimplementsInjectionDAO{// 实现接口中的方法publicvoidsave(String arg){ System.out.println("保存数据"+ arg); }}
// 测试importorg.junit.Test;@RunWith(BlockJUnit4ClassRunner.class)publicclassTestInjectionextendsUnitTestBase{ publicTestInjection(){super("classpath:spring-injection.xml"); }@Testpublic void testSetter(){InjectionServiceservice =super.getBean("injectionService"); service.save("保存的数据"); }@Testpublic void testCons() {InjectionServiceservice =super.getBean("injectionService"); service.save("保存的数据"); }}
bean的配置:
id:id是整个ioc容器中,bean的标识class:具体要实例化的类scope:作用域constructorarguments:构造器的参数properties:属性autowiring mode:自动装配的模式lazy-initializationmode:懒加载模式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是针对字节数组封装的资源
publicinterfaceResourceLoader{ResourcegetResource(String location);}
ResourceLoader
classpath:Loaded from the classpath;file:Loadedasa URL, from the filesystem;http:Loadedasa URL;
案例:
publicclassMResourceimplementsApplicationContextAware{privateApplicationContext applicationContext;@OverridepublicvoidsetApplicationContext(ApplicationContext applicationContext)throwsBeansException{this.applicationContext = applicationContext; }publicvoidresource(){ Resource resource = applicationContext.getResource("classpath:config.txt"); System.out.println(resource.getFilename()); }}
// 单元测试类importcom.test.base.UnitTestBase;@RunWith(BlockJUnit4ClassRunner.class)publicclassTestResourceextendsUnitTestBase{ publicTestResource() {super("classpath:spring-resource.xml"); }@Testpublic void testResource() {MResourceresource =super.getBean("mResource");try{ resource.resource(); }catch(IOExceptione){ e.printStackTrace(); } }}
http://www.springframework.org/schema/beans/spring-beans.xsd">
bean的定义与学习:
@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
@ServicepublicclassSimpleMovieLister{privateMovieFinder movieFinder;@AutowiredpublicSimpleMovieLister(MovieFinder movieFinder){this.movieFinder = movieFinder; }}
@RepositorypublicclassJpaMovieFinderimplementsMovieFinder{}
类的自动检测以及Bean的注册
http://www.springframework.org/schema/beans/spring-beans.xsd">
类被自动发现并注册bean的条件:
用@Component,@Repository,@Service,@Controller注解或者使用@Component的自定义注解
@Required用于bean属性的setter方法
@Autowired注解
privateMovieFinder movieFinder;@AutowiredpublicvoidsetMovieFinder(MovieFinder movieFinder){this.movieFinder = movieFinder;}用于构造器或成员变量@AutowiredprivateMovieCatalog movieCatalog;privateCustomePreferenceDap customerPreferenceDao;@AutowiredpublicMovieRecommender(CustomerPreferenceDao customerPreferenceDao){this.customerPreferenceDao = customerPreferenceDao;}
@Autowired注解
使用这个注解,如果找不到bean将会导致抛出异常,可以使用下面代码避免,每个类只能有一个构造器被标记为required=true.
publicclassSimpleMovieLister{privateMovieFinder movieFinder;@Autowired(required=false)publicvoidsetMovieFinder(MovieFinder movieFinder){this.movieFinder = movieFinder; }}
spring是一个开源框架,spring是用j2ee开发的mvc框架,spring boot呢就是一个能整合组件的快速开发框架,因为使用maven管理,所以很便利。至于spring cloud,就是微服务框架了。
spring是一个轻量级的Java开发框架,是为了解决企业应用开发的复杂性而创建的框架,框架具有分层架构的优势.
spring这种框架是简单性的,可测试性的和松耦合的,spring框架,我们主要是学习控制反转IOC和面向切面AOP.
// 知识点springiocspringaopspringormspringmvcspringwebservicespringtransactionsspringjmsspringdataspringcachespringbootspringsecurityspringschedule
spring ioc为控制反转,控制反向,控制倒置,
Spring容器是 Spring 框架的核心。spring容器实现了相互依赖对象的创建,协调工作,对象只要关系业务逻辑本身,IOC最重要的是完成了对象的创建和依赖的管理注入等,控制反转就是将代码里面需要实现的对象创建,依赖的代码,反转给了容器,这就需要创建一个容器,用来让容器知道创建对象与对象的关系.(告诉spring你是个什么东西,你需要什么东西)
xml,properties等用来描述对象与对象间的关系
classpath,filesystem,servletContext等用来描述对象关系的文件放在哪里了.
控制反转就是将对象之间的依赖关系交给了容器管理,本来是由应用程序管理的对象之间的依赖的关系.
spring ioc体系结构
BeanFactoryBeanDefinition
spring ioc是spring的核心之一,也是spring体系的基础,在spring中主要用户管理容器中的bean.spring的IOC容器主要使用DI方式实现的.BeanFactory是典型的工厂模式,ioc容器为开发者管理对象间的依赖关系提供了很多便利.在使用对象时,要new object()来完成合作.ioc:spring容器是来实现这些相互依赖对象的创建和协调工作的.(由spring`来复杂控制对象的生命周期和对象间的)
所有的类的创建和销毁都是由spring来控制,不再是由引用它的对象了,控制对象的生命周期在spring.所有对象都被spring控制.
ioc容器的接口(自己设计和面对每个环节):
BeanFactory工厂模式
publicinterfaceBeanFactory{ String FACTORY_BEAN_PREFIX ="&";ObjectgetBean(String name)throwsBeansException;ObjectgetBean(String name, Class requiredType)throwsBeansException;booleancontainsBean(String name);booleanisSingleton(String name)throwsNoSuchBeanDefinitionException;ClassgetType(String name)throwsNoSuchBeanDefinitionException; String[] getAliases(String name); }
BeanFactory三个子类:ListableBeanFactory,HierarchicalBeanFactory和AutowireCapableBeanFactory,实现类是DefaultListableBeanFactory.
控制反转就是所有的对象都被spring控制.ioc动态的向某个对象提供它所需要的对象.通过DI依赖注入来实现的.如何实现依赖注入ID,在Java中有一特性为反射,它可以在程序运行的时候进行动态的生成对象和执行对象的方法,改变对象的属性.
publicstaticvoidmain(String[] args){ ApplicationContextcontext=newFileSystemXmlApplicationContext("applicationContext.xml"); Animal animal = (Animal)context.getBean("animal"); animal.say();}
// applicationContext.xml
publicclassCatimplementsAnimal{privateString name;publicvoidsay(){ System.out.println("dashu"); }publicvoidsetName(String name){this.name = name; }}
publicinterfaceAnimal{publicvoidsay();}
// beanprivateStringid;privateStringtype;privateMap properties=new HashMap();
publicstaticObjectnewInstance(StringclassName) { Class cls =null;Objectobj =null;try{ cls = Class.forName(className); obj = cls.newInstance(); }catch(ClassNotFoundException e) {thrownewRuntimeException(e); }catch(InstantiationException e) {thrownewRuntimeException(e); }catch(IllegalAccessException e) {thrownewRuntimeException(e); }returnobj;}
核心是控制反转(IOC)和面向切面(AOP),spring是一个分层的JavaSE/EE的轻量级开源框架.
web:
struts,spring-mvc
service:
spring
dao:
mybatis,hibernate,jdbcTemplate,springdata
spring体系结构
ioc
// 接口publicinterfaceUserService{publicvoidaddUser();}// 实现类publicclassUserServiceImplimplementsUserService{@OverridepublicvoidaddUser(){ System.out.println("dashucoding"); }}
配置文件:
http://www.springframework.org/schema/beans/spring-beans.xsd">
测试:
@Testpublicvoiddemo(){ String xmlPath ="com/beans.xml"; ApplicationContext applicationContext =newClassPathXmlApplicationContext(xmlPath); UserService userService = (UserService) applicationContext.getBean("userServiceId"); userService.addUser();}
依赖注入:
classDemoServiceImpl{privatedaDao daDao;}
创建service实例,创建dao实例,将dao设置给service.
接口和实现类:
publicinterfaceBookDao{publicvoidaddBook();}publicclassBookDaoImplimplementsBookDao{@OverridepublicvoidaddBook(){ System.out.println("dashucoding"); }}
publicinterfaceBookService{publicabstractvoidaddBook();}publicclassBookServiceImplimplementsBookService{privateBookDao bookDao;publicvoidsetBookDao(BookDao bookDao){this.bookDao = bookDao; }@OverridepublicvoidaddBook(){this.bookDao.addBook(); }}
配置文件:
http://www.springframework.org/schema/beans/spring-beans.xsd">
测试:
@Testpublicvoiddemo(){ String xmlPath ="com/beans.xml"; ApplicationContext applicationContext =newClassPathXmlApplicationContext(xmlPath); BookService bookService = (BookService) applicationContext.getBean("bookServiceId"); bookService.addBook();}
IDE建立Spring项目
File—>new—>project—>Spring
spring
// Server.javapublicclassServer{ privete String name;publicvoidsetName(String name){this.name = name; }publicvoidputName(){ System.out.println(name); }}
// Main.javapublicclassMain{publicstaticvoidmain(String[] args){ ApplicationContext context =newClassPathXmlApplicationContext("spring-config.xml"); Server hello = (Server)context.getBean("example_one"); hello.putName(); }}
spring-config.xml:
http://www.springframework.org/schema/beans/spring-beans.xsd">
使用Maven来声明Spring库.Maven是一个项目管理的工具,maven提供了开发人员构建一个完整的生命周期框架.Maven的安装和配置,需要的是JDK 1.8,Maven,Windows,配置jdk,JAVA_HOME变量添加到windows环境变量.下载Apache Maven,添加 M2_HOME 和 MAVEN_HOME,添加到环境变量PATH,值为%M2_HOME%\bin.执行mvn –version命令来显示结果.
Maven启用代理进行访问,找到文件路基,找到/conf/settings.xml,填写代理,要阿里的哦.
Maven中央存储库地址:
https://search.maven.org/
// xmlorg.jvnet.localizerlocalizer1.8
// pom.xmljava.nethttps://maven.java.net/content/repositories/public/
Maven添加远程仓库:
// pom.xmljava.nethttps://maven.java.net/content/repositories/public/JBoss repositoryhttp://repository.jboss.org/nexus/content/groups/public/
Maven依赖机制,使用Maven创建Java项目.
junitjunit4.11test
Maven打包:
4.0.0com.dashucodingNumberGeneratorjar1.0-SNAPSHOT
spring框架:
publicinterfaceHelloWorld{publicvoidsayHello();}publicclassSpringHelloWorldimplementsHelloWorld{publicvoidsayHello(){ System.out.println("Spring Hello"); }}publicclassStrutsHelloWorldimplementsHelloWorld{publicvoidsayHello(){ System.out.println("Struts Hello"); }}publicclassHelloWorldServie{privateHelloWorld helloWorld;publicHelloWorldService(){this.helloWorld =newStrutsHelloWorld(); }}
控制反转:
publicclassHelloWorldService{privateHelloWorld helloWorld;publicHelloWorldService(){ }publicvoidsetHelloWorld(HelloWorld helloWorld){this.helloWorld = helloWorld; }publicHelloWorldgetHelloWorld(){returnthis.helloWorld; }}
ioc创建了HelloWorldService对象.
spring->HelloProgram.javahelloworld->HelloWorld.javaHelloWorldService.javaimpl实现类->SpringHelloWorld.javaStrutsHelloWorld.javaresources->beans.xml// 总结一个spring:HelloProgram.java接口:实现类:资源:beans.xml
// HelloWorld.javapublicinterfaceHelloWorld{publicvoidsayHello();}// public class HelloWorldService {privateHelloWorld helloWorld;publicHelloWorldService(){ }publicvoidsetHelloWorld(HelloWorld helloWorld){this.helloWorld = helloWorld; }publicHelloWorldgetHelloWorld(){returnthis.helloWorld; }}
// SpringHelloWorld.javapublicclassSpringHelloWorldimplementsHelloWorld{@OverridepublicvoidsayHello(){ System.out.println("Spring Hello!"); }}// StrutsHelloWorld.javapublicclassStrutsHelloWorldimplementsHelloWorld{@OverridepublicvoidsayHello(){ System.out.println("Struts Hello!"); }}
// HelloProgram.javapublicclassHelloProgram{publicstaticvoidmain(String[] args){ ApplicationContext context =newClassPathXmlApplicationContext("beans.xml"); HelloWorldService service = (HelloWorldService) context.getBean("helloWorldService"); HelloWorld hw= service.getHelloWorld(); hw.sayHello(); }}
// beans.xml
http://www.springframework.org/schema/beans/spring-beans.xsd">
ioc创建beans实现类springHelloWorld,创建一个helloWorldService类,beans.xml实现参数导入:
// helloWorldService// springHelloWorld// Hello Program.javaApplicationContext context =newClassPathXmlApplicationContxt("beans.xml");HelloWorldService service = (HelloWorldService) context.getBean("helloWorldService");HelloWorld hw = service.getHelloWorld();hw.sayHello();// HelloWorldServicepublicclassHelloWorldService{privateHelloWorld helloWorld;publicHelloWorldService(){ }publicvoidsetHelloWorld(HelloWorld helloWorld){this.helloWorld = helloWorld; }publicHelloWorld = getHelloWorld() {returnthis.helloWorld; }}
// beans.xml
spring库地址:
http://maven.springframework.org/release/org/springframework/spring/
hello-world:
publicclassHelloWorld{privateString name;publicvoidsetName(String name){this.name = name; }publicvoidprintHello(){ System.out.println("Spring"+ name); }}
// xml
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
// 执行publicclassApp{publicstaticvoidmain(String[] args){ ApplicationContext context =newClassPathXmlApplicationContext("applicationContext.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloBean"); obj.printHello(); }}
喜欢的朋友可以加我的技术圈:454377428