- @Configuration 应用于一个类,相当于建立一个applicationContext.xml文件
- @ComponentScan 相当于xml配置文件中的<context:component-scan base-package="cn.chenxiejia.entity"/>
- @Bean 相当于xml配置文件中的
@Configuration @ComponentScan("cn.chenxiejia.service")
public class SpringConfig {
@Bean(name="uu",initMethod = "init",destroyMethod = "close")
@Scope("singleton") @Lazy
public UserDao u1(){
var u = new UserDao();
return u;
}
}
- @Scope 此注解一般在类上,IoC是否为单例 @Scope("singleton") ,相当于 配置文件中
- @Import 导入其它配置类,相当于配置文件中的
@Configuration("ccc")
@ComponentScan("cn.chenxiejia.entity")
@Import(DruidConfig.class)
public class AppConfig {
@Bean(initMethod = "start",destroyMethod = "end") @Scope("singleton")
public Teacher t1(){
Teacher t = new Teacher(10,"周老师");
System.out.println(t);
return t;
}
@Bean("t2") @Scope("prototype")
public Teacher t2(){
Teacher t = new Teacher(22,"李老师");
return t;
}
}
- @Value注入属性值
@Value("1111")
private int id;
@Value("1.2")
private double money;
@Value("李青")
private String name;
@Value("true")
private boolean isstu;
@Value("java,php,html,mysql,php,html")
private String[] arrstr;
@Value("10,20,30,40")
private int[] arrint;
@Value("#{'java,php,html,mysql,php,html'.split(',')}")
private Set set;
@Value("#{'java,php,html,mysql,php,html'.split(',')}")
private List list;
@Value("#{{name:'lisi',age:18,is:true}}")
private Map<String,Object> map;
@Value("#{t1.name}")
private String tname;
@Value("#{student.id * 2}")
private int num;
@Autowired
private Teacher t3;
//t.properties books=php,java,javascript,html,java,java,php
@Value("${books}")
private String[] tarr;
@Value("#{'${books}'.split(',')}")
private Set tset;
//t.properties db.map={name:'wangwu',age:28,age:22,age:33,is:true}
@Value("#{${db.map}}")
private Map<String,Object> tmap;
//注入List t1 t2 teacher分别是IoC容器的bean
@Value("#{{t1,t2,teacher}}")
private Teacher[] teachers;
@Value("#{{t1,t2,teacher}}")
private List listts;
- @Autowired自动装配
//如果IoC容器没有,就装配null,不报错
@Autowired (required = false)
//自动装配,先根据类型,如果类型有多,再根据属性的变量名,如果没有变量名,报错。
@Autowired
public User user;
//自动装配,先根据类型,如果类型有多,再根据属性的变量名,如果没有变量名,可以指定
@Qualifier("uu")。
@Autowired @Qualifier("uu")
private UserDao userdao;