1. 程式人生 > >javaEE顛覆者程式碼一

javaEE顛覆者程式碼一

ps : 只是單純的打了一遍 /
javaEE顛覆者第一章
1.3.1 依賴注入
我是直接用maven來建立專案的
關於maven的安裝 這裡就不在多加描述了
直接開始吧

建立maven專案

這是pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion
>
4.0.0</modelVersion> <groupId>com.wisely</groupId> <artifactId>spring4</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.6.RELEASE</version> </dependency> </dependencies> <build> <plugins> <plugin
>
<groupId>org.apache.maven.plugins</groupId> <artifactId>maven-comipler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build> </project>

(1)編寫功能類的bean

package spring4.main;

import org.springframework.stereotype.Service;

@Service//宣告一個spring管理bean
public class FunctionService {
    public String sayHello(String word) {
        return "hello "+word+"!";
    }
}

(2)使用功能類的bean

package spring4.main;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserFunctionService {
    @Autowired//注入bean  等價於 Inject   Resource
    FunctionService functionService;

    public String sayHello(String word) {
        return functionService.sayHello(word); 
    }
}

(3)配置類

package spring4.main;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration //配置類宣告
@ComponentScan("spring4.main")//掃描包名下所有的帶有 @Service @Componet  @Repository  @Controller註解的類,自動註冊為bean
public class DiConfig {

}

(4)執行

package spring4.main;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context 
                        = new AnnotationConfigApplicationContext(DiConfig.class);//使用AnnotationConfigApplicationContext 作為Spring容器 接受一個配置類作為引數
        UserFunctionService userFunctionService
                        =context.getBean(UserFunctionService.class);
        System.out.println(userFunctionService.sayHello("helloword"));//獲取宣告的bean
        context.close();
    }
}

結果