1. 程式人生 > 其它 >面試(涉及技術三)

面試(涉及技術三)

實體類:

package com.ly.pojo;

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

@Component
public class User {
    private String name;

    public String getName() {
        return name;
    }
    @Value(
"凌雲") public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "name='" + name + '\'' + '}'; } }

配置類:

package com.ly.config;

import com.ly.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration //代表這是一個配置類,相當於beans.xml @ComponentScan("com.ly.pojo") public class lyconfig { @Bean //註冊一個bean,相當於bean標籤; //方法的名字相當於bean標籤中的id屬性 //這個方法的返回值,相當於bean標籤中的class屬性
public User user(){ return new User(); } }

測試類:

import com.ly.config.lyconfig;
import com.ly.pojo.User;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(lyconfig.class);
        User getUser = context.getBean("user", User.class);
        System.out.println(getUser.getName());
    }
}

純java的配置在Springboot非常常見!