1. 程式人生 > 其它 >spring的學習日記-spring-IOC-使用純註解的方式開發

spring的學習日記-spring-IOC-使用純註解的方式開發

我們在使用完全註解開發的時候,我們需要注意:建立一個類,代替xml配置,使用@Configuration註解代替xml,

再在這個類裡面提夠一個實體類的方法,返回new 這個物件,使用@Bean註解代替xml中的bean

pojo層:

package com.fu.pojo;

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

@Component
public class User {
    @Value("張三")
    
private String name; @Value("15") private int age; public User(String name, int age) { this.name = name; this.age = age; } public User() { } public String getName() { return name; } public void setName(String name) { this.name = name; }
public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } }

config層(代替xml配置的類所在的層):

package com.fu.config;

import com.fu.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean("user")
    public User getUser(){
        return new User();
    }

}

測試類:

/*  我們在spring中使用純註解的開發,我們完全捨棄了xml的配置檔案
        但是我們需要寫一個類,使用@Configuration註解使其成為我們代替品,代替xml的配置檔案

 */

import com.fu.config.AppConfig;
import com.fu.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {

    public static void main(String[] args) {

        //獲取IOC容器
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        User user = context.getBean("user", User.class);
        System.out.println(user);
    }
}

測試結果: