概述
基于 Java 的配置选项,可以使你在不用配置 XML 的情况下编写大多数的 Spring
1、编写一个实体类 User
package com.fanlan.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component//将这个类标注为Spring的一个组件,放到容器中
public class User {
private String name;
public String getName() {
return name;
}
@Value("fanlan")
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + ''' +
'}';
}
}
2、新建个config配置类
package com.fanlan.config;
import com.fanlan.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration//代表这是一个配置类
@Import(Uesrconfig1.class)//导入合并其他配置类,类似于配置文件中的 inculde 标签
public class Uesrconfig {
@Bean//通过方法注册一个bean,这里的返回值就Bean的类型,方法名就是bean的id
public User user(){
return new User();
}
}
package com.fanlan.config;
import org.springframework.context.annotation.Configuration;
@Configuration//配置类
public class Uesrconfig1 {
}
3、测试
import com.fanlan.config.Uesrconfig;
import com.fanlan.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringTest {
@Test
public void test(){
ApplicationContext ctx = new AnnotationConfigApplicationContext(Uesrconfig.class);
User user = ctx.getBean("user", User.class);
System.out.println(user.toString());
}
}
4.测试结果
User{name='fanlan'}
最后
以上就是重要柜子为你收集整理的Spring 基于 Java 的配置的全部内容,希望文章能够帮你解决Spring 基于 Java 的配置所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复