1. 程式人生 > 其它 >Spring-02(使用JavaConfig進行配置)

Spring-02(使用JavaConfig進行配置)

使用JavaConfig進行配置

①寫一個實體類

package pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

public class User {
    @Value("xcy")
    private  String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        
this.name = name; } }

②定義一個JavaConfig類,在類上使用@Configuration 註解,將會使當前類作為一個 Spring 的容器來使用,用於完成 Bean 的建立。在該 JavaConfig 的方法上使用@Bean,將會使一個普通方法所返回的結果變為指定名稱的 Bean 例項。

package config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import
pojo.User; @Configuration public class Myconfig { @Bean public User getUser(){ return new User(); } }

進行這個程式碼後,相當於建立了一個 id=“getUser”的bean物件。也可以在bean後面新增名字比如@Bean("user")相當於建立了一個id=“user”的bean物件。

③進行測試

import config.Myconfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import pojo.User; public class MyTest { public static void main(String[] args) { /* 注意之前是 ApplicationContext Context = new ClassPathXmlApplicationContext("applicationContext.xml"); 後面是ClassPathXmlApplicationContext,現在javaconfig配置檔案後面是AnnotationConfigApplicationContext 且之前後面跟的是xml檔名,而用JavaConfig進行配置後面跟的是配置類。 */ ApplicationContext Context = new AnnotationConfigApplicationContext(Myconfig.class); User getUser = Context.getBean("getUser", User.class); System.out.println(getUser.getName()); } }