1. 程式人生 > >第65節:Java後端的學習之Spring基礎

第65節:Java後端的學習之Spring基礎

標題圖

Java後端的學習之Spring基礎

如果要學習spring,那麼什麼是框架,spring又是什麼呢?學習spring中的iocbean,以及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.beansorg.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-annotationsspring提供的註解可以作為位元組的程式碼叫元資料註解,處理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 iocspring的核心之一,也是spring體系的基礎,在spring中主要使用者管理容器中的bean.springIOC容器主要使用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,HierarchicalBeanFactoryAutowireCapableBeanFactory,實現類是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_HOMEMAVEN_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後帥氣小夥,良好的開發習慣;獨立思考的能力;主動並且善於溝通
簡書部落格: 達叔小生
https://www.jianshu.com/u/c785ece603d1

結語

  • 下面我將繼續對 其他知識 深入講解 ,有興趣可以繼續關注
  • 小禮物走一走 or 點贊