spring常用注解及演示

1. @Configuration 应用于一个类,相当于建立一个applicationContext.xml文件

2. @ComponentScan 相当于xml配置文件中的<context:component-scan base-package="cn.chenxiejia.entity"/>

3. @Bean 相当于xml配置文件中的<bean id="" class=""></bean>

@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;
}
}

4. @Scope 此注解一般在类上,IoC是否为单例 @Scope("singleton") ,相当于 配置文件中<bean id="ul" class="cn.chenxiejia.entity.User" scope="prototype"></bean>

5. @Import 导入其它配置类,相当于配置文件中的<import resource="beans-lisi.xml">

@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;
}
}

6. @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<String> set;
@Value("#{'java,php,html,mysql,php,html'.split(',')}")
private List<String> 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<String> tset;
//t.properties db.map={name:'wangwu',age:28,age:22,age:33,is:true}
@Value("#{${db.map}}")
private Map<String,Object> tmap;
//注入List<Teacher> t1 t2 teacher分别是IoC容器的bean
@Value("#{{t1,t2,teacher}}")
private Teacher[] teachers;
@Value("#{{t1,t2,teacher}}")
private List<Teacher> listts;

7. @Autowired自动装配

//如果IoC容器没有,就装配null,不报错
@Autowired (required = false)
//自动装配,先根据类型,如果类型有多,再根据属性的变量名,如果没有变量名,报错。
@Autowired
public User user;
//自动装配,先根据类型,如果类型有多,再根据属性的变量名,如果没有变量名,可以指定
@Qualifier("uu")。
@Autowired @Qualifier("uu")
private UserDao userdao;

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值