我正在尝试测试我的Spring网络应用程序,但我遇到了一些问题.
我在我的maven中添加了一个测试类
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testName() throws Exception {
List<UserEntity> userEntities = userService.getAllUsers();
Assert.assertNotNull(userEntities);
}
}
Run Code Online (Sandbox Code Playgroud)
但是NullPointerException
当我尝试运行此测试时,我得到了一个用户服务.IntelliJ说"无法自动装配.没有找到'UserService'类型的bean.添加后@RunWith(SpringJUnit4ClassRunner.class)
,我得到了这个例外
java.lang.IllegalStateException: Neither GenericXmlContextLoader nor AnnotationConfigContextLoader was able to detect defaults, and no ApplicationContextInitializers were declared for context configuration
Run Code Online (Sandbox Code Playgroud)
我怎么解决呢?我想我需要在我的tomcat服务器上运行这个测试但是我如何使用IntelliJ进行测试?(比如命令'mvn clean install tomcat7:run-war-only')
我想使用Spring RestTemplate进行简单的HTTP POST.Wesb服务接受参数中的JSON,例如:{"name":"mame","email":"email@gmail.com"}
public static void main(String[] args) {
final String uri = "url";
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson message converter
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
// create request body
String input = "{ \"name\": \"name\", \"email\": \"email@gmail.com\" }";
JsonObject request = new JsonObject();
request.addProperty("model", input);
// set headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Basic " + "xxxxxxxxxxxx");
HttpEntity<String> entity = new HttpEntity<String>(request.toString(), headers);
// send request and parse result
ResponseEntity<String> response = restTemplate
.exchange(uri, HttpMethod.POST, …
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用休息服务,我正在发布一些数据,RestTemplate
postForObjectMethod
但是我得到了一个null响应,即使我可以在有效负载中看到请求和响应.
[更新]我正在使用拦截器实施ClientHttpRequestInterceptor
,如果我删除它,我得到了响应.
[PS:该服务配置为POST,理想情况下它应该是GET,原因很明显,但我仍然很好奇为什么没有响应作为帖子的一部分来,即使我可以在http日志中看到相同.]
配置基于Spring MVC 4的应用程序
应用背景:
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</list>
</property>
<property name="interceptors">
<list>
<bean class="com.sipl.interceptors.LoggingRequestInterceptor" />
</list>
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
杰克逊POM
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
拦截器类
public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {
final static Logger logger = LoggerFactory.getLogger(LoggingRequestInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
traceRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
traceResponse(response); …
Run Code Online (Sandbox Code Playgroud) 我有各种协议,我的系统正在使用.我标记了一个接口并提供了适当的实现.例如SSHprotocol
,HttpProtocol
两个工具Protocol
.我将来可能会添加多个.现在我有一个课程如下: -
class Test {
@Autowired
private Protocol protocol;
public void getProtocol(String name) {
return protocol;
}
}
Run Code Online (Sandbox Code Playgroud)
本getProtocol
应返回一个Protocol
基于对象Protocol
的名字.总之,我希望Spring根据name参数自动装配特定的bean.春天是否支持这个?我可以有多个@Autowired
相应的限定符.但这可能会让我用相应的自动装配注释编写10-15个变量.但这太多的代码使得难以管理.工厂可能是一个替代方案,但如何解决我的问题?
我正在尝试这样做。
我有一个对象列表(自定义对象),我想将它们全部保存在 Redis 中的单个寄存器中,是否可以以某种方式将它们保存为 ajax?我正在阅读有关杰克逊的文章,但我不知道如何理解。
到目前为止我只有这个
@Autowired
private StringRedisTemplate redisTmpl;
Run Code Online (Sandbox Code Playgroud)
我可以这样保存
redisTmpl.opsForValue().set("foo", "bar");
Run Code Online (Sandbox Code Playgroud)
效果很好,但我想保存我的对象列表(使用这个StringRedisTemplate
.
知道怎么做吗?
或者也许使用另一种方式?但我需要用一键保存所有列表。
谢谢
我正在使用@ConfigurationProperties
来跟踪我的属性。一切正常,包括子配置的类成员。Properties
加载良好,框架使用 getter 来确定“上下文名称”。但是我在尝试验证时遇到了麻烦,它不验证子属性。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>be.test</groupId>
<artifactId>test</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Run Code Online (Sandbox Code Playgroud)
应用程序属性:
test.value = 4
test.value2 = 6
test.sub.subValue = 9
Run Code Online (Sandbox Code Playgroud)
验证应用程序.java
@SpringBootApplication
public class ValidationApplication implements CommandLineRunner
{
private final TestProperties properties;
public ValidationApplication(TestProperties properties) {
this.properties = …
Run Code Online (Sandbox Code Playgroud) 我正在尝试构建一个 Spring Shell 应用程序。我能够成功运行我的应用程序,但它会立即退出@启动并且不等待用户输入。JLineShell promptLoop 方法中似乎没有保留。
我正在用 mainClassName = "org.springframework.shell.Bootstrap" 构建一个 jar。
我的 spring-shell-plugin.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="com.zailab" />
</beans>
Run Code Online (Sandbox Code Playgroud)
我的主课:
public class Main {
public static void main(String[] args) throws IOException{
Bootstrap.main(args);
}
}
Run Code Online (Sandbox Code Playgroud)
我的命令类:
@Component
public class BuildCommand implements CommandMarker {
@CliAvailabilityIndicator({"echo"})
public boolean isCommandAvailable() {
return true;
}
@CliCommand(value = "echo", help = "Echo a message")
public String echo(
@CliOption(key = { "", "msg" }, mandatory …
Run Code Online (Sandbox Code Playgroud) 我尝试在Spring中插入后检索id,但此解决方案不起作用:
String sqlquery2 = "INSERT into tab (attr1,attr2) VALUES (?,?)";
String sql1 ="select last_insert_id()";
jdbcTemplateObject.update(sqlquery2, value1, value2);
int id = jdbcTemplateObject.update(sql1);
Run Code Online (Sandbox Code Playgroud) 我已经用java轻松地将小文件上传到亚马逊s3存储桶。但是当我上传 50MB 的大文件时,花费的时间太长,我什至没有得到异常,但文件没有上传。我的代码很简单
s3client.putObject(new PutObjectRequest("dev.rivet.media.web", "all.wav",new File(file path)));
Run Code Online (Sandbox Code Playgroud)
谁能建议我解决这个问题
所以我在我的Main课程中得到了这个:
public class Main extends JFrame {
public static void main(String[] args) {
JFrame Launch = new JFrame();
Launch.setSize(800, 400);
Launch.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Launch.setContentPane(new StartView());
Launch.setTitle("De Hartige Hap");
Launch.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
现在让我们说我在那个小组(" StartView()
")
并onClick
在一个按钮上,我想改变帧的内容窗格..
我该怎么做?
public class StartView extends javax.swing.JPanel {
public StartView() {
initComponents();
}
private void OrderButtonActionPerformed(java.awt.event.ActionEvent evt) {
/*instead of Launch.setContentPane(new StartView());
*it has to be (new otherView())
*/
}
Run Code Online (Sandbox Code Playgroud) 我编写了一段代码来检查@Async
Spring框架中的注释行为.
@RequestMapping( value="/async" , method = RequestMethod.GET)
public ModelAndView AsyncCall(HttpServletRequest request)
{
async1();
async2();
return new ModelAndView("firstpage");
}
@Async
private void async1(){
System.out.println("Thread 1 enter");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread 1 exit");
}
@Async
private void async2(){
System.out.println("Thread 2 enter");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread 2 exit");
}
Run Code Online (Sandbox Code Playgroud)
此代码的输出如下.
Thread 1 enter
Thread 1 exit
Thread …
Run Code Online (Sandbox Code Playgroud) 我有两个类Drug
和medicalDrawer
.
我搜索了一种方法来获取所有medicalDrawer
未使用的内容Drug
@Entity
public class Drug {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long drugId;
@OneToOne
private MedicalDrawer medicalDrawer;
}
@Entity
public class MedicalDrawer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long medicalDrawerId;
private String name;
}
Run Code Online (Sandbox Code Playgroud) spring ×11
java ×9
spring-mvc ×3
amazon-s3 ×1
asynchronous ×1
file ×1
jdbctemplate ×1
jframe ×1
jpanel ×1
json ×1
junit ×1
maven ×1
redis ×1
rest ×1
resttemplate ×1
spring-data ×1
spring-rest ×1
spring-shell ×1
sql ×1
swing ×1
validation ×1
web-services ×1