Java後端的學習之Spring

若是要學習spring,那麼什麼是框架,spring又是什麼呢?學習spring中的ioc和bean,以及aop,IOC,Bean,AOP,(配置,註解,api)-springFramework.java

Java後端的學習之Spring基礎

 

各類學習的知識點:web

spring expression language
spring integration
spring web flow
spring security
spring data
spring batch

spring網站:spring

http://spring.io/數據庫

Java後端的學習之Spring基礎

 

http://spring.io/projects/spring-frameworkexpress

Java後端的學習之Spring基礎

 

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

什麼是框架,爲何要用框架:數組

什麼是框架:

Java後端的學習之Spring基礎

 

Java後端的學習之Spring基礎

 

框架就是別人制定好的一套規則和規範,你們在這個規範或者規則下進行工做,能夠說,別人蓋好了樓,讓咱們住.

Java後端的學習之Spring基礎

 

Java後端的學習之Spring基礎

 

軟件框架是一種半成品,具備特定的處理流程和控制邏輯,成熟的,能夠不斷升級和改進的軟件.

使用框架重用度高,開發效率和質量的提升,容易上手,快速解決問題.

spring ioc容器

Java後端的學習之Spring基礎

 

接口,是用於溝通的中介物的,具備抽象化,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
  1. @Repository用於註解DAO類爲持久層
  2. @Service用於註解Service類爲服務層
  3. @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爲控制反轉,控制反向,控制倒置,

Java後端的學習之Spring基礎

 

Java後端的學習之Spring基礎

 

Java後端的學習之Spring基礎

 

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/

Java後端的學習之Spring基礎

 

// 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框架:

Java後端的學習之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();
 }
}
相關文章
相關標籤/搜索