完全不使用Spring的xml,全部交给Java来做,在Springboot中很常见
User.java:
package com.kakafa.pojo;
import org.springframework.beans.factory.annotation.Value;
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 + '\'' +
'}';
}
}
KakafaConfig:
package com.kakafa.config;
import com.kakafa.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class KakafaConfig {
@Bean
public User getUser(){
return new User();
}
}
test:
import com.kakafa.config.KakafaConfig;
import com.kakafa.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(KakafaConfig.class);//注意这里不加双引号
User getUser = (User)context.getBean("getUser");
System.out.println(getUser.getName());
}
}