不用配置的spring
使用java的方式配置spring
新特性:完全不需要spring的xml配置了,全权交给java来做
javaConfig是spring的一个子项目,在spring4之后,他成为了一个核心功能
先来一个User类,
用@Configuration//类似来实现
实体类
package com.kuang.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
public class User{
private String name;
public String getName() {
return name;
}
@Value("测试1")
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
配置文件
package com.kuang.config;
import com.kuang.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration//类似<beans>
@ComponentScan("com.kuang.pojo")//查找位置
@Import(Config2.class)//引入对象的注解比如说要配置多个
public class Config {
//注册一个bean,就相当于我们之前写的一个bean,
// 这个方法的名字就相当于bean标签中的id属性,
// 返回值就相当于class属性
@Bean
public User getUser(){//getUser相当于bean中的id
return new User();
}
}
测试类
import com.kuang.config.Config;
import com.kuang.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
public static void main(String[] args) {
//如果完全使用配置类方式去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载!
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
User getUser = context.getBean("getUser", User.class);
System.out.println(getUser.getName());
}
}
@Component:组件,放在类上,说明这个类被spring管理了,就是bean!
@Component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层:下面那三个注解和@Component一样的功能
dao层【@Repository】
service层【@Service】
controller层【@Controller】
@Value(“测试1”)//相当于
@Import(Config2.class)//引入对象的注解比如说要配置多个
@Configuration//类似导入这个注解之后相当于搞一个配置文件xml