Spring纯注解开发,有点强!!
Java仓库
共 5122字,需浏览 11分钟
·
2022-08-25 18:44
-
正文
1
Spring3.0引入了纯注解开发的模式,框架的诞生是为了简化开发,那注解开发就是简化再简化。Spring的特性在整合MyBatis方面体现的淋漓尽致哦
2
以前跟老韩学习SE时他就说:
3
注解开发前,配置Bean时是在xml里将class分别写在Bean标签里,然后起id,就像这样
<bean id="a" class="yu7daily.Dao.Daoimpl.A" />
注解开发后,配置Bean时首先将xml里的<Bean>标签删掉,然后在类上添加@Component注解即可
@Component("a")
public class A implements AA {
public void save() {
System.out.println("book dao save ..." );
}
}
<context:component-scan base-package="yu7daily.Dao"/>
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
A aa = (A) ctx.getBean("a");
bookService.save();
}
4
对于@Component还有衍生的三个注解:
5
@Configuration
@ComponentScan("yu7daily")
public class Config {...}
@Component("a")
@Scope("prototype")
public class A implements AA {
public void save() {
System.out.println("hello~");
}
}
6
@Service
public class A implements AA {
@Autowired
private B b;
}
@Repository("b")
public class B implements BB {
@Autowired
@Qualifier("a") //注入指定的对象名称
private AA aa;
public void save() {
aa.save();
}
}
@Repository("a")
public class A implements AA {
@Value("hello java")
private String str;
public void save() {
System.out.println(str);
}
}
运行结果:hello
@Configuration
@ComponentScan("yu7daily")
@PropertySource("test.properties")
public class SpringConfig {
}
@Repository("a")
public class A implements AA {
@Value("${name}")
private String str;
public void save() {
System.out.println(str);
}
}
运行结果:lanyangyang
7
<artifactId>spring-jdbc</artifactId>和13<artifactId>mybatis-spring</artifactId>
@Configuration
@ComponentScan("yu7daily")
@PropertySource("classpath:jdbc.properties")
4@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {...}
ApplicationContext ACC = new AnnotationConfigApplicationContext(SpringConfig.class);
AccountService acc = ACC.getBean(AccountService.class);
评论