我在一本书中读到,每当我们想要基于Java的配置并想要定义bean时,我们都会使用@Bean注释。但是当我这样做时,我得到了错误:The annotation @Bean is disallowed for this location。我的豆是:
package com.mj.cchp.bean;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull;
import org.springframework.context.annotation.Bean;
import com.mj.cchp.annotation.Email;
@Bean
public class UserBean {
@NotNull
@Email
private String email;
@NotNull
private String firstName;
@NotNull
private String lastName;
@Digits(fraction = 0, integer = 10)
private String phoneNo;
@NotNull
private String role;
public String getEmail() {
return email;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getPhoneNo() {
return phoneNo;
}
public String getRole() {
return role;
}
public void setEmail(String email) {
this.email = email;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public void setRole(String role) {
this.role = role;
}
}
Run Code Online (Sandbox Code Playgroud)
该@Bean注释是定义一个Bean在Spring容器被加载。它类似于指定的xml配置
<bean id="myId" class="..."/>
Run Code Online (Sandbox Code Playgroud)
应该在Configuration文件(java)中使用。这与你的相似applicationContext.xml
@Configuration
@ComponentScan("...")
public class AppConfig{
@Bean
public MyBean myBean(){
return new MyBean();
}
}
Run Code Online (Sandbox Code Playgroud)
在@Bean, @Configuration和其他新引入的注解会做的正是你在一个XML配置做什么。
| 归档时间: |
|
| 查看次数: |
14458 次 |
| 最近记录: |