Spring基本配置(1)
来源:互联网 发布:python核心编程第3版 编辑:程序博客网 时间:2024/04/27 18:02
首先将Spring所需要的包导入:
首先是带xml的方式
spring.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hw" class="com.yc.spring.HelloWorld" scope="prototype">
</bean>
</beans>
HelloWorld.class:
package com.yc.spring;
import org.springframework.stereotype.Component;
public class HelloWorld {
public HelloWorld(){
System.out.println("helloworld的构造函数");
}
public void say(){
System.out.println("helloworld spring");
}
}
下面是使用注解方式:
package com.yc.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//用这个类来代替xml文件
@Configuration
@ComponentScan("com.yc")
public class Appconfig {
}
HelloWorld.class:
package com.yc.spring;
import org.springframework.stereotype.Component;
@Component //注解方式所需要的
public class HelloWorld {
public HelloWorld(){
System.out.println("helloworld的构造函数");
}
public void say(){
System.out.println("helloworld spring");
}
}
Test.class:
package spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.yc.spring.Appconfig;
import com.yc.spring.HelloWorld;
import junit.framework.TestCase;
public class Test extends TestCase {
public void testApp(){//传统方式
HelloWorld hw=new HelloWorld();
hw.say();
}
public void testApp02(){//spring 控制反转方式
//1读取sring.xml文件 创建spring容器(完成helloWorld对象的创建)
ApplicationContext con=new ClassPathXmlApplicationContext("spring.xml");
HelloWorld hw=(HelloWorld) con.getBean("hw");
hw.say();
}
//注解方式
public void testApp03(){//spring 控制反转方式
//1读取sring.xml文件 创建spring容器(完成helloWorld对象的创建)
ApplicationContext con=new AnnotationConfigApplicationContext(Appconfig.class);
//HelloWorld hw=con.getBean(HelloWorld.class);//这样就产生了依赖,必须有HelloWorld这个类
//hw.say();
HelloWorld hw=(HelloWorld) con.getBean("helloWorld");//约定为类名第一个字母为小写 最前面的HelloWorld可面向接口 不产生依赖
hw.say();
}
}
- Spring基本配置(1)
- 1、Spring的基本配置
- Spring+监听器+Quartz集群(1)——基本配置
- spring+hibernate整合(基本配置)
- spring mvc 基本配置
- Spring MVC3 基本配置
- Spring AOP基本配置
- spring mvc基本配置
- Spring 基本配置
- Spring MVC基本配置
- Mybatis-spring基本配置
- Spring+hibernate基本配置
- spring基本配置
- Spring的基本配置
- Spring AOP基本配置
- Spring xml基本配置
- Spring基本配置
- Spring MVC 基本配置
- UVA 11732 "strcmp()" Anyone?
- poj 1019 Number Sequence 数学
- 一点一点学maven(10)——eclipse实现maven模块化开发
- 用AXD和JLINK调试u-boot方法与步骤
- linux实用程序(2)
- Spring基本配置(1)
- QDUOJ 87 - n^n的末位数字
- Spring中如何配置部署多个数据库
- android:碎片的生命周期
- FaceBook Share
- leetCode_Majority Element II【多数投票法】
- 人脸识别经典算法实现(三)——LBP算法
- python建立数据库
- CodeForces 698 A. Vacations(dp)