若是要学习spring,那么什么是框架,spring又是什么呢?学习spring中的ioc和bean,以及aop,IOC,Bean,AOP,(配置,注解,api)-springFramework.java
各类学习的知识点:web
spring expression language spring integration spring web flow spring security spring data spring batch
spring网站:spring
http://spring.io/数据库
http://spring.io/projects/spring-frameworkexpress
spring是一种开源框架,是为了解决企业应用开发的复杂性问题而建立的,如今的发展已经不止于用于企业应用了.编程
spring是一种轻量级的控制反转(IoC)和面向切面(AOP)的容器框架.windows
一句名言:spring带来了复杂的javaee开发的春天.后端
jdbc orm oxm jms transactions websocket servlet web portlet aop aspects instrumentation messaging beans core context spel
springmvc+spring+hibernate/ibatis->企业应用api
什么是框架,为何要用框架:数组
什么是框架:
框架就是别人制定好的一套规则和规范,你们在这个规范或者规则下进行工做,能够说,别人盖好了楼,让咱们住.
软件框架是一种半成品,具备特定的处理流程和控制逻辑,成熟的,能够不断升级和改进的软件.
使用框架重用度高,开发效率和质量的提升,容易上手,快速解决问题.
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
元注解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>
使用Maven来声明Spring库.Maven是一个项目管理的工具,maven提供了开发人员构建一个完整的生命周期框架.Maven的安装和配置,须要的是JDK 1.8,Maven,Windows,配置jdk,JAVA_HOME变量添加到windows环境变量.下载Apache Maven,添加 M2_HOME 和 MAVEN_HOME,添加到环境变量PATH,值为%M2_HOME%in.执行mvn –version命令来显示结果.
Maven启用代理进行访问,找到文件路基,找到/conf/settings.xml,填写代理,要阿里的哦.
Maven中央存储库地址:
https://search.maven.org/
// xml <dependency> <groupId>org.jvnet.localizer</groupId> <artifactId>localizer</artifactId> <version>1.8</version> </dependency> // pom.xml <repositories> <repository> <id>java.net</id> <url>https://maven.java.net/content/repositories/public/</url> </repository> </repositories>
Maven添加远程仓库:
// pom.xml <project ...> <repositories> <repository> <id>java.net</id> <url>https://maven.java.net/content/repositories/public/</url> </repository> </repositories> </project> <project ...> <repositories> <repository> <id>JBoss repository</id> <url>http://repository.jboss.org/nexus/content/groups/public/</url> </repository> </repositories> </project>
Maven依赖机制,使用Maven建立Java项目.
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency>
Maven打包:
<project ...> <modelVersion>4.0.0</modelVersion> <groupId>com.dashucoding</groupId> <artifactId>NumberGenerator</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version>
spring框架:
public interface HelloWorld{ public void sayHello(); } public class SpringHelloWorld implements HelloWorld { public void sayHello(){ System.out.println("Spring Hello"); } } public class StrutsHelloWorld implements HelloWorld { public void sayHello(){ System.out.println("Struts Hello"); } } public class HelloWorldServie { private HelloWorld helloWorld; public HelloWorldService(){ this.helloWorld = new StrutsHelloWorld(); } }
控制反转:
public class HelloWorldService{ private HelloWorld helloWorld; public HelloWorldService(){ } public void setHelloWorld(HelloWorld helloWorld){ this.helloWorld = helloWorld; } public HelloWorld getHelloWorld(){ return this.helloWorld; } }
ioc建立了HelloWorldService对象.
spring->HelloProgram.java helloworld-> HelloWorld.java HelloWorldService.java impl实现类-> SpringHelloWorld.java StrutsHelloWorld.java resources->beans.xml // 总结 一个spring:HelloProgram.java 接口: 实现类: 资源:beans.xml // HelloWorld.java public interface HelloWorld { public void sayHello(); } // public class HelloWorldService { private HelloWorld helloWorld; public HelloWorldService(){ } public void setHelloWorld(HelloWorld helloWorld){ this.helloWorld = helloWorld; } public HelloWorld getHelloWorld(){ return this.helloWorld; } } // SpringHelloWorld.java public class SpringHelloWorld implements HelloWorld { @Override public void sayHello() { System.out.println("Spring Hello!"); } } // StrutsHelloWorld.java public class StrutsHelloWorld implements HelloWorld { @Override public void sayHello() { System.out.println("Struts Hello!"); } } // HelloProgram.java public class HelloProgram { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); HelloWorldService service = (HelloWorldService) context.getBean("helloWorldService"); HelloWorld hw= service.getHelloWorld(); hw.sayHello(); } } // beans.xml <beansxmlns="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="springHelloWorld" class="com.spring.helloworld.impl.SpringHelloWorld"></bean> <bean id="strutsHelloWorld" class="com.spring.helloworld.impl.StrutsHelloWorld"></bean> <bean id="helloWorldService" class="com.spring.helloworld.HelloWorldService"> <property name="helloWorld" ref="springHelloWorld"/> </bean> </beans> <propertyname="helloWorld"ref="strutsHelloWorld"/>
ioc建立beans实现类springHelloWorld,建立一个helloWorldService类,beans.xml实现参数导入:
// helloWorldService // springHelloWorld // Hello Program.java ApplicationContext context = new ClassPathXmlApplicationContxt("beans.xml"); HelloWorldService service = (HelloWorldService) context.getBean("helloWorldService"); HelloWorld hw = service.getHelloWorld(); hw.sayHello(); // HelloWorldService public class HelloWorldService { private HelloWorld helloWorld; public HelloWorldService(){ } public void setHelloWorld(HelloWorld helloWorld){ this.helloWorld = helloWorld; } public HelloWorld = getHelloWorld() { return this.helloWorld; } } // beans.xml <bean id="名称" class="路径"/> <bean id="helloWorldService" class=""> <property name="helloWorld" ref="springHelloWorld"/> </bean>
spring库地址:
http://maven.springframework.org/release/org/springframework/spring/
hello-world:
public class HelloWorld { private String name; public void setName(String name) { this.name = name; } public void printHello() { System.out.println("Spring" + name); } } // 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-3.0.xsd"> <bean id="helloBean" class=""> <property name="name" value="dashu" /> </bean> </beans> // 执行 public class App { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloBean"); obj.printHello(); } }