首页 > 代码库 > Spring笔记
Spring笔记
Spring的框架组成:它是对web层、业务层、数据访问层的每层都有解决方案;web层:Spring MVC;持久层:JDBC Template ;业务层:Spring的Bean管理;
一、核心部分之IOC
实例;接口:HelloService.java
public interface HelloService { public void sayHello(); }
接口实现类:HelloServiceImpl.java
public class HelloServiceImpl implements HelloService { private String info; public void setInfo(String info) { this.info = info; } public void sayHello() { System.out.println("Hello Spring..."+info); } }
配置文件:applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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属性为类起个标识. --> <bean id="userService" class="cn.itcast.spring3.demo1.HelloServiceImpl"> <!-- 使用<property>标签注入属性 --> <property name="info" value="传智播客"/> </bean> </beans>
测试: SpringTest1.java
public class SpringTest1 { @Test // 传统方式 public void demo1() { // 造成程序紧密耦合. HelloService helloService = new HelloServiceImpl(); helloService.sayHello(); } @Test // Spring开发 public void demo2() { // 创建一个工厂类. ApplicationContext applicationContext = new ClassPathXmlApplicationContext( "applicationContext.xml"); HelloService helloService = (HelloService) applicationContext .getBean("userService"); helloService.sayHello(); } @Test // 加载磁盘路径下的配置文件: public void demo3() { ApplicationContext applicationContext = new FileSystemXmlApplicationContext( "applicationContext.xml"); HelloService helloService = (HelloService) applicationContext .getBean("userService"); helloService.sayHello(); } @Test public void demo4(){ // ClassPathResource FileSystemResource BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("applicationContext.xml")); HelloService helloService = (HelloService) beanFactory.getBean("userService"); helloService.sayHello(); } }
Spring笔记
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。