Spring配置元数据的三种方式
2020-07-29 本文已影响0人
奔向学霸的路上
- 基于java配置方式
@Configuration
public class BeanConfiguration {
@Bean
public Account account(){
return new Account("001001001");
}
@Bean
public User user(Account account){
return new User("张三",18,account);
}
@Bean
public User userNoAccount(){
return new User("张三",18,null);
}
}
- 基于注解方式
@Repository
public class JpaMovieFinder implements MovieFinder {
// implementation elided for clarity
}
@Service
public class SimpleMovieLister {
private MovieFinder movieFinder;
public SimpleMovieLister(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
}
- 基于xml方式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 空值的user -->
<bean id="userNoValue" class="intron.spring.entity.User"></bean>
<!-- 带值的user -->
<bean id="user" class="intron.spring.entity.User">
<property name="name" value="张三"></property>
<property name="age" value="18"></property>
</bean>
<!-- 全参构造,使用成员属性索引对应 -->
<bean id="userOnIndex" class="intron.spring.entity.User">
<constructor-arg index="0" value="张三"></constructor-arg>
<constructor-arg index="1" value="18"></constructor-arg>
</bean>
<!-- 全参构造,使用成员属性类型对应 -->
<bean id="userOnType" class="intron.spring.entity.User">
<constructor-arg type="java.lang.String" value="张三"></constructor-arg>
<constructor-arg type="int" value="18"></constructor-arg>
</bean>
</beans>