001--@Configuration和@Bean 註解(方式一)

環境Idea + maven,相關依賴

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.13.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

 

  1. @Configuration註解相當於原先spring的xml配置文件,用配置類代替配置文件

 

  1. @Bean註解 在配置了@Configuration的配置類中使用
  2. @Bean註解配置在方法名上,在IOC容器中的名稱就是方法名
  3. 改別名則傳入別名例如@Bean("別名")

完整例子

package bean;

public class HelloWorld {
    String hello="Hello demo";

    @Override
    public String toString() {
        return "HelloWorld{" +
                "hello='" + hello + '\'' +
                '}';
    }
}
package config;

import bean.HelloWorld;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {
    @Bean("hello")
    public HelloWorld hello(){
        return new HelloWorld();
    }
}

單元測試 

package config;

import bean.HelloWorld;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;


import static org.junit.Assert.*;

public class ConfigTest {

    @Test
    public void test1(){
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
        HelloWorld hello = (HelloWorld) applicationContext.getBean("hello");
        System.out.println(hello);
    }
}

輸出結果

通過修改@Bean(“參數”)可以更改別名

發佈了259 篇原創文章 · 獲贊 15 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章