两种方式:
第一种@Configuration + @Bean第二种@Configuration+@ComponentScan+@@Component配置类:
package com.henry.Appconfig; import com.henry.POJO.User; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan(basePackages = "com.henry.POJO") public class Appconfig { //第一种@Configuration + @Bean 第二种@Configuration+@ComponentScan+@@Component // @Bean public User getUser(){ return new User(); } }POJO类:
package com.henry.POJO; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class User { private String name; @Value("DAMING") public void setName(String name) { this.name = name; } public String getName() { return name; } }测试类:
import com.henry.Appconfig.Appconfig; import com.henry.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(Appconfig.class); //User user = context.getBean("getUser"); 一定要注意这里!! 注册方法名,或者 改成如下 User user = (User) context.getBean(User.class); //Component 默认注册类名 System.out.println(user.getName()); } }