
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>
複製程式碼
使用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/

// 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();
}
}
複製程式碼
達叔小生:往後餘生,唯獨有你 You and me, we are family ! 90後帥氣小夥,良好的開發習慣;獨立思考的能力;主動並且善於溝通 簡書部落格: 達叔小生 www.jianshu.com/u/c785ece60…
結語
- 下面我將繼續對 其他知識 深入講解 ,有興趣可以繼續關注
- 小禮物走一走 or 點贊